我有两个功能,当我运行程序时,只有按钮点击计数器功能似乎运行。它们都是单独工作的

问题描述 投票:1回答:4

基本上我正在寻找一种方法来使两个函数一起运行。想法是单击按钮会生成1-20之间的随机数。然后将其发送到if语句,该语句根据是否低于或等于10或更高来显示不同的文本。这个工作正常。然后我添加了按钮点击计数器(它也能正常工作)我为代码创建,计算按钮被点击的次数,因为它为用户生成一个新的数字。现在,这只会导致按钮点击次数被计算,并且不再显示生成的随机数或文本。我确信这是一个简单的修复。有人可以帮我解释一下我哪里出错了吗?谢谢任何帮助过的人。

首先,我将展示一个带注释的版本,并且所有初学者级编码器都会查找具有更多解释的内容。然后是一个裸代码版本,适合任何寻找不那么混乱的人。

//Commented Version:

    <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Random Number Generator with Button Counter</title>
</head>

<body>

    <!--This is the button that calls the function ranNum()-->
    <input type="button" onClick="ranNum()" id="btn" value="Generate Random 
    Number Between 1 and 20" />

    <!--Here is where the Randomly Generated Number is stored in numText 
    and the text to go with it.-->
    <p id="numText"></p>

    <!--Here is where the number of times the button has been clicked is 
    stored.-->
    <p>The button was pressed <span id="displayCount">0</span> times.</p>


     <script>

        window.onload = function () {

          /*Generates a random number from 1 to 20. this number is carried 
          into the IF statement using the variable name GenerateNumber. The 
          if statement checks if the number is less than or equal to 10 and 
          gives out an appropriate response if so. If it dosen't meet the 
          criteria, it will call the else statement.
        */
            function ranNum() {

                var GeneratedNumber = Math.floor(Math.random() * 20) + 1;

                var conclusion

                if (GeneratedNumber <= 10) {

                    conclusion = `The number generated ${GeneratedNumber} is 
                    less than or equal to 10`;

                } else {

                    conclusion = `The number generated ${GeneratedNumber} is 
                    greater than 10`;

                 } //END of if statement

                //The given conclusion is taken here and stored/displayed on 
                the page using the id numText.
                document.getElementById("numText").innerHTML = conclusion;

            } //END of ranNum

        //Global variable set to store the count.
        var count = 0;

        //Global variable set to store button count.
        var button = document.getElementById("btn");

        /*This is where the stored count is moved to be dispayed on the page 
        through the p tag with
        the id of displayCount.*/
        var display = document.getElementById("displayCount");

        /*This is the function which has been to set to count on button 
        clicks and increment by 1 every time.*/
        button.onclick = function storeClickCount() {
                count++;
                display.innerHTML = count;
            }//END of storeClickCount

        }//END of window.onload

    </script>

</body>

</html>

//Version with no comments:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Random Number Generator with Button Counter</title>
</head>

<body>

    <input type="button" onClick="ranNum()" id="btn" value="Generate Random 
    Number Between 1 and 20" />

     <p id="numText"></p>

     <p>The button was pressed <span id="displayCount">0</span> times.</p>


     <script>

        window.onload = function () {

            function ranNum() {

                var GeneratedNumber = Math.floor(Math.random() * 20) + 1;

                var conclusion

                if (GeneratedNumber <= 10) {

                    conclusion = `The number generated ${GeneratedNumber} is 
                    less than or equal to 10`;

                } else {

                    conclusion = `The number generated ${GeneratedNumber} is 
                    greater than 10`;

                 } 

                document.getElementById("numText").innerHTML = conclusion;

            } 

        var count = 0;

        var button = document.getElementById("btn");

        var display = document.getElementById("displayCount");

        button.onclick = function storeClickCount() {
                count++;
                display.innerHTML = count;
            }

        }

    </script>

</body>

</html>
javascript html
4个回答
1
投票

使用addEventListener(),您可以绑定window.onload范围内的多个函数。看看我的例子。

window.onload = function() {

  function ranNum() {
    var GeneratedNumber = Math.floor(Math.random() * 20) + 1;
    var conclusion;
    if (GeneratedNumber <= 10) {
      conclusion = `The number generated ${GeneratedNumber} is less than or equal to 10`;
    } else {
      conclusion = `The number generated ${GeneratedNumber} is greater than 10`;
    }
    document.getElementById("numText").innerHTML = conclusion;
  }

  var count = 0;
  var button = document.getElementById("btn");
  var display = document.getElementById("displayCount");

  button.addEventListener('click',ranNum);
  button.addEventListener('click',function storeClickCount() {
    count++;
    display.innerHTML = count;
  });

}
<input type="button" id="btn" value="Generate Random Number Between 1 and 20" />
<p id="numText"></p>
<p>The button was pressed <span id="displayCount">0</span> times.</p>

1
投票

问题是ranNum不是一个全局函数,因为它隐藏在window.onload回调中,因此HTML onclick属性的值没有可见性。

解:

ranNum移动到回调之外,进入全局范围。此解决方案的缺点是您继续使用两种方法来处理click事件:(1)通过HTML onclick属性值,以及(2)通过JS代码中的onclick =处理程序赋值。对于任何试图理解或管理代码的人来说,这都令人困惑。

替代方案:

不要在HTML中使用onclick属性,而是从qzxswpoi已有的单击处理程序中调用ranNum

button

建议:使用浏览器控制台验证错误。当您单击按钮并且找不到 button.onclick = function storeClickCount() { ranNum(); // <<------- count++; display.innerHTML = count; } 函数时,它会显示错误。


0
投票

改变了你的代码。整个过程包含在一个ranNum而不是两个单独的function()

functions()

0
投票

这个给你!我刚刚为你创建了一个按钮点击功能,其中包含你的两个功能;)祝你好运

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Random Number Generator with Button Counter</title> </head> <body> <input type="button" onClick="ranNum()" id="btn" value="Generate Random Number Between 1 and 20" /> <p id="numText"></p> <p>The button was pressed <span id="displayCount">0</span> times.</p> <script> var numText = document.getElementById("numText"); var displayCount = document.getElementById("displayCount"); var count = 0; function ranNum() { var generatedNumber = Math.floor(Math.random() * 20) + 1; count++; var conclusion = ''; if (generatedNumber <= 10) { conclusion = `The number generated ${generatedNumber} is less than or equal to 10`; } else { conclusion = `The number generated ${generatedNumber} is greater than 10`; } numText.innerHTML = conclusion; displayCount.innerHTML = count; }; </script> </body> </html>

https://codepen.io/greg_o/pen/dgxgKL?editors=1111
window.onload = function(){
let count = 0;
const button = document.getElementById("btn");
var display=document.getElementById("displayCount");

function storeClickCount() {
    count++;
    display.innerHTML = count;
  };


function ranNum() {
    let GeneratedNumber = Math.floor(Math.random() * 20) + 1;
    let conclusion;

    if (GeneratedNumber <= 10) {
      conclusion = `The number generated ${GeneratedNumber} is less than or equal to 10`;
    } else {
      conclusion = `The number generated ${GeneratedNumber} is greater than 10`;
    }

    document.getElementById("numText").innerHTML = conclusion;
  }

ranNum();

button.onclick = function buttonClick(){
    ranNum();
    storeClickCount()
}}
© www.soinside.com 2019 - 2024. All rights reserved.