$(this) .prop() 只在第一次工作

$(this) .prop() only works the first time

本文关键字:第一次 工作 prop this      更新时间:2023-09-26

我想创建一个引擎,它问一个随机问题(在本例中为随机数)。当它回答正确时,(通过按右键)它会询问一个新的。 我的代码只在第一次工作。右键始终是第一次按下的

按钮
$( 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");}
});
});

如果你需要 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>

问题是你在哪里设置新数字

var number = Math.floor(Math.random() * 4 + 1);  //<--- you use 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>