Мои две функции JS, которые работают отдельно, но не вместе - PullRequest
0 голосов
/ 23 сентября 2019

Итак, я попытался создать функцию, которая очищает экран и отправляет мне предупреждение в зависимости от того, какую кнопку я нажал.Я могу очистить экран без каких-либо проблем, а также получить предупреждение, но я не могу сделать так, чтобы оба происходили одним нажатием кнопки.

<head>
<script>
    function cleartext() {
        document.getElementById("text0").style.display = "none";
    }   

    function btnchecklist() {
        document.getElementById("btn1").onclick = function() {
            alert("hello1");
        }
        document.getElementById("btn2").onclick = function() {
            alert("hello2");
        }
        document.getElementById("btn3").onclick = function() {
            alert("hello3");
        }
    }       
</script>
</head>

<body>
    <div id="text0"> 
        <p> some text </p>
    </div>     

    <div id="btn-group">
        <button id="btn1" onclick="cleartext(); btnchecklist();"> 1 </button>
        <button id="btn2" onclick="cleartext(); btnchecklist();"> 2 </button>
        <button id="btn3" onclick="cleartext(); btnchecklist();"> 3 </button>    
    </div>    
</body>     

Ответы [ 2 ]

0 голосов
/ 23 сентября 2019

Проверьте мой ответ ниже PS.это не лучшее решение, если вы объяснили мне, что именно вы хотите сделать, может быть, я предоставлю более четкий ответ.

So I have tried to create a function that clears the screen and sends me an alert based on what button I have pressed. I
can clear the screen without any problems and also receive the alert but I can't seem to make both happen with one press
of a button.

<head>
  <script>
    function cleartext() {
      document.getElementById("text0").style.display = "none";
    }

    window.onload = function () {
      document.getElementById("btn1").onclick = function () {
        alert("hello1");
        cleartext();
      }
      document.getElementById("btn2").onclick = function () {
        alert("hello2");
        cleartext();
      }
      document.getElementById("btn3").onclick = function () {
        alert("hello3");
        cleartext();
      }
    };  
  </script>
</head>

<body>
  <div id="text0">
    <p> some text </p>
  </div>

  <div id="btn-group">
    <button id="btn1"> 1 </button>
    <button id="btn2"> 2 </button>
    <button id="btn3"> 3 </button>
  </div>
</body>
0 голосов
/ 23 сентября 2019

Лучше используйте этот код.

Передайте элемент button в функцию btnchecklist (this) и в своей функции получите идентификатор вашего переданного элемента и отобразите предупреждение с соответствующим текстом.

function cleartext() {
    document.getElementById("text0").style.display = "none";
  }

  function btnchecklist(element) {
    //Read id of element
    switch (el.id) {
      case "btn1":
        alert("hello1"); //Output in case of element id is btn1
        break;
      case "btn2":
        alert("hello2");
        break;
      case "btn3":
        alert("hello3");
        break;
    }
  }
<div id="text0">
  <p> some text </p>
</div>

<div id="btn-group">
<!-- Pass element to your btnchecklist function (this) -->
  <button id="btn1" onclick="cleartext();btnchecklist(this)"> 1 </button>
  <button id="btn2" onclick="cleartext();btnchecklist(this)"> 2 </button>
  <button id="btn3" onclick="cleartext();btnchecklist(this)"> 3 </button>
</div>

Более короткий, но более сложный код:

  var aButtons = document.querySelectorAll("#btn-group>button"); //Get all buttons in btn-group
    aButtons.forEach(function(oButton){ //Loop buttons
    oButton.addEventListener("click", function(el){ //Add click event listener to each button
        var regex = new RegExp(/([\d+])/); //Regulr Expression to find the number in your bvutton id
      document.getElementById("text0").style.display = "none";
      alert("hello" + el.target.id.match(regex)[0]); //Alert "hello" Text + number in your button id
    });
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...