简体   繁体   English

我无法使这几行简单的代码正常工作,也不知道为什么

[英]I can't make these few simple line of code work correctly and have no idea why

I tried to this simple exercise , i did get it to work but not correctly. 我尝试了这个简单的练习,但确实无法正常工作。 It's supposed to give you a random number between 0 and 1000 as you click a button. 单击按钮时,应该为您提供0到1000之间的随机数。 When you click the button again , it creates another random number , if its bigger than the last one , it displays it. 再次单击该按钮时,它将创建另一个随机数,如果它大于最后一个随机数,则会显示该随机数。 If it is not , it does nothing. 如果不是,则不执行任何操作。 And while it does this , it counts how many times it had run the function. 在执行此操作的同时,它会计算运行该功能的次数。 The one i made did give me random numbers but sometimes , it displayed smaller numbers than the last one and sometimes it didn't. 我制作的数字确实给了我随机数字,但有时,它显示的数字比上一个数字小,有时却没有。 I can't figure out why. 我不知道为什么。 I suspect it might be because of the line of code where i tried to change what the button does. 我怀疑这可能是因为我试图更改按钮的功能所在的代码行。

<!DOCTYPE html>
<html>
<head>
<input id="btn" type="button" onclick="initiate(1)" value="Click me!"><br>
<script>
function geid(id) {
    return document.getElementById(id);
}
var count = 0;

function initiate(n) {
    var x = n;
    n = Math.floor(Math.random() * 1000);
    document.getElementById("btn").onclick = function () {
        initiate(n);
    }

    if (n > x) {
        geid("fid").innerHTML = n;
        count += 1;
        geid("fid2").innerHTML = count + " times";

    } else {
        count += 1;
        geid("fid2").innerHTML = count + " times";

    }
}
</script>

</head>

<body>
Number : <div id="fid">0</div>
Tried <div id="fid2">0</div>

</body>

</html>

The problem is that you're always changing the onclick function, regardless of whether the newly chosen n value is greater than the previous value ( x ) or not. 问题是,无论新选择的n值是否大于先前的值( x ),都始终在更改onclick函数。

Take this example: suppose that the statement Math.floor(Math.random()*1000); 举个例子:假设语句Math.floor(Math.random()*1000); produces this sequence of values when you run it multiple times: 100, 500, 200, 300. 当您多次运行它时,将生成此值序列:100、500、200、300。

With the first click, the function was called as initiate(1) , the spot fid1 was set to hold 100 , and the onclick handler was set to call initiate(100) . 第一次单击时,该函数称为initiate(1) ,现场fid1设置为保持100 ,而onclick处理程序设置为调用fid1 initiate(100)

With the second click, the function was called as initiate(100) , the spot fid1 was set to hold 500 , and the onclick handler was set to call initiate(500) . 第二次单击时,该函数称为initiate(100) ,现场fid1设置为容纳500 ,而onclick处理程序被设置为调用fid1 initiate(500) So far so good. 到现在为止还挺好。

With the third click, the function was called as initiate(500) , the spot fid1 was left unchanged at 500 , and the onclick handler was set to call initiate(200) . 第三次单击,该函数被称为fid1 initiate(500) ,点fid1500保持不变,并且onclick处理程序设置为调用fid1 initiate(200) Um... 嗯...

With the fourth click, the function was called as initiate(200) , the spot fid1 was set to hold 300 , and the onclick handler was set to call initiate(300) . 第四次单击时,该函数称为initiate(200) ,现场fid1设置为保持300 ,而onclick处理程序被设置为调用fid1 initiate(300)

So the issue is that if you want to change the handler to hold always the current value in fid1 , then you shouldn't change the handler unless n > x . 因此,问题在于,如果要更改处理程序以始终将当前值保存在fid1 ,那么除非n > x否则不应更改处理程序。

There seem to be several errors in here of how things are placed. 这里的事物放置方式似乎存在一些错误。 This rearrangement should work: 这种重新安排应该起作用:

function geid(id){return document.getElementById(id);}
var count = 0;
    var x = 0;

function initiate(){
    n =  Math.floor(Math.random()*1000);

    if(n>x){
        x = n;
        geid("fid").innerHTML = n;
        count +=1;
        geid("fid2").innerHTML = count + " times";

    }else{
        count +=1;
        geid("fid2").innerHTML = count + " times";
    }
}

document.getElementById("btn").onclick = function(){
    initiate();
}

There is plenty of room for optimization, but this should be pretty clear. 有足够的优化空间,但这应该很清楚。


Update 更新

Here is a version that I think is relatively clean: 这是我认为比较干净的版本:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="btn" type="button" value="Click me!"><br>
<p>Number : <span id="number">0</span></p>
<p>Tried <span id="tried">0</span></p>
<script>
    function geid(id){return document.getElementById(id);}
    var count = 0, highest = 0, number = geid("number"), tried = geid("tried");

    geid("btn").onclick = function(){
        var random =  Math.floor(Math.random() * 1000);
        count += 1;
        tried.innerHTML = count + " times";

        if (random > highest){
            highest = random;
            number.innerHTML = random;
        }
    }
</script>
</body>
</html>

I would still probably wrap the whole thing in an IIFE in order to not expose anything on the global scope, but other than that, this code is now reasonably readable, and reasonably efficient, I believe. 我可能仍会将整个内容包装在IIFE中,以免在全局范围内暴露任何内容,但除此之外,我相信这段代码现在已经相当合理地可读且相当有效。

here's a clean version 这是一个干净的版本

<!DOCTYPE html>
<html>
  <head>
    <script>
      (function(){
        var count = 0, lastRandom = 0, click;
        click = function () {
          var random;
          random = Math.floor(Math.random()*1000);
          if (random > lastRandom) {
            document.getElementById("fid").innerHTML = random;
          }
          count += 1;
          document.getElementById("fid2").innerHTML = count+" times";
        };
        window.addEventListener('load',function(){
          document.getElementById('btn').addEventListener('click',click,false);
        },false);
      });
    </script>
  </head>
  <body>
    <input id="btn" type="button" value="Click me!"><br>
    Number : <div id="fid">0</div>
    Tried <div id="fid2">0</div>
  </body>
</html>

Don't just copy paste this. 不要只是复制粘贴此内容。 If it works (I can't test it right now), then try to understand what it's doing. 如果它有效(我现在无法测试),请尝试了解它的作用。 If you can't then please ask, I can add some comments if you need them 如果不能,请提出要求,如果需要,我可以添加一些评论

If you click the button really fast this change won't take effect.... 如果您快速单击按钮,此更改将不会生效。

document.getElementById("btn").onclick = function(){ // right here
  initiate(n);                                       // so not a good idea.
}

Just put this: 只需输入以下内容:

document.getElementById("btn").onclick = function(){
    initiate(n);
}

Outside your initiate function 在您的启动功能之外

like: 喜欢:

function geid(id){return document.getElementById(id);}
var count = 0;

function initiate(n){
    var x = n;
    n =  Math.floor(Math.random()*1000);


if(n>x){
    geid("fid").innerHTML = n;
    count +=1;
    geid("fid2").innerHTML = count + " times";

}else{
    count +=1;
    geid("fid2").innerHTML = count + " times";

}


}

window.onload = function() {



    document.getElementById("btn").onclick = function(){
      var n = 10; // some number    
      initiate(n);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您是否知道为什么我的代码无法正常工作,而单击时却无法获取数字? - Do you have any idea why my code does not work and I can not get the numbers while clicking 为什么这个非常简单的javascript / jquery代码无法正常工作 - Why this very simple javascript/jquery code won't work correctly 我写了一个简单的粒子过滤器,它不能用于数百个以上的粒子。 我不知道为什么 - I wrote a simple particle filter and it won't work with more than a few hundred particles. I can't tell why 为什么这种简单的一行JavaScript代码不起作用? - Why doesn't this simple, one line javascript code work? 我无法使这个简单的正则表达式正常工作 - I can't get this simple regex to work correctly 我有一个简单的网站,想在鼠标悬停时更改字体大小,但此代码不起作用。为什么? - I have a simple site and want to change my font-size when the mouse is over but this code don't work.Why? 为什么我不能让这个简单的 CSS 转换工作? - Why can’t I get this simple CSS transition to work? 如何使美化代码在一行中起作用? - How can I make prettify code work in one line? 为什么我不能使该实体代码在浏览器中正确显示? - Why can't I get this entity code to display correctly in a browser? Extjs 6-无法使alwaysOnTop正常工作 - Extjs 6 - Can't make alwaysOnTop work correctly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM