gpt4 book ai didi

javascript - jQuery/JS - 变量似乎没有更新?

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:14 25 4
gpt4 key购买 nike

我希望用户单击一个 DIV 元素并让它向 JavaScript 中的一个变量加 1,然后随着该变量值的变化发生不同的事情。当我第一次点击 div 元素时,它显示“你在这里!”但是当我第二次单击 div 元素时……似乎什么也没有发生。变量似乎没有更新。

var $test = 0;
$( document ).ready(function() {

if ($test == 0) {
$("#textbox").click(function() {
$(textbox).text("You and here!");
$test = $test + 1;
});
};

if ($test == 1) {
$("#textbox").click(function() {
$(textbox).text("Now, you are there!");
$test = $test + 1;
});
};
});

最佳答案

您需要检查点击处理程序中的条件

$(document).ready(function () {
//declare it as a closure variable instead of addint it to the global scope
var test = 0;
$("#textbox").click(function () {
//check the value of test here
if (test == 0) {
$(textbox).text("You and here!");
} else if (test == 1) { //or just else
$(textbox).text("Now, you are there!");
}
//increment the value of test
test++;
});
});

关于javascript - jQuery/JS - 变量似乎没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20988139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com