简体   繁体   English

$(this).prop()仅在第一次使用时有效

[英]$(this) .prop() only works the first time

I want to create an engine, that asks a random question (in this case, a random number). 我想创建一个引擎,询问一个随机问题(在这种情况下,是一个随机数)。 When its answered correctly,(by pressing the right button) it asks a new one. 正确回答后(按右按钮),它会询问一个新的。 My code only works the first time. 我的代码只能在第一次使用。 Afther that the right button is always the one, that was pressed the first time 此外,右键始终是第一次按下的按钮

$( document ).ready(function() {

var number = Math.floor(Math.random() * 4 + 1);
$('#my_div').text(number);


$('button').click(function() {
    var buttonNumber = $(this).prop('id');

    if(buttonNumber == number){
        $('#my_div2').text(buttonNumber);

        setTimeout(function(){
        var number = Math.floor(Math.random() * 4 + 1); 
        $('#my_div').text(number);
        }, 1);
    }
    else{ $('#my_div2').text("wrong");}
});

});

in case you need html 万一你需要HTML

<html>

<div id="buttons">
        <button id="1">1</button>
        <button id="2">2</button>
        <button id="3">3</button>
        <button id="4">4</button>
        <button id="5">5</button>
</div>

<div id="my_div"> X </div>

<div id="my_div2"> X </div>
</html>

Problem is where you set the new number 问题是您在哪里设置新号码

var number = Math.floor(Math.random() * 4 + 1);  //<--- you use var

That will not replace the number variable declared before it. 那不会替换之前声明的数字变量。 So remove the var 因此删除var

 $( document ).ready(function() { var number = Math.floor(Math.random() * 4 + 1); $('#my_div').text(number); $('button').click(function() { var buttonNumber = $(this).prop('id'); if(buttonNumber == number){ $('#my_div2').text(buttonNumber); setTimeout(function(){ number = Math.floor(Math.random() * 4 + 1); $('#my_div').text(number); }, 1); } else{ $('#my_div2').text("wrong");} }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="buttons"> <button id="1">1</button> <button id="2">2</button> <button id="3">3</button> <button id="4">4</button> <button id="5">5</button> </div> <div id="my_div"> X </div> <div id="my_div2"> X </div> 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM