gpt4 book ai didi

javascript - 达到 IF 条件后停止函数

转载 作者:行者123 更新时间:2023-11-30 08:38:51 28 4
gpt4 key购买 nike

我有一个按钮,每次单击时,都会将 1 添加到变量中。当此变量超过 5 时,将触发警报。然而,此后触发器仍不断激活。我尝试使用 == 而不是 > 进行检查,但它做同样的事情。有什么想法吗?

http://jsfiddle.net/1345qam8/

// Declare the variable
var generic_counter = 0;
// Log the variable
console.log(generic_counter);
// When button is clicked, add 1 to the variable
$(document).ready(function() {
$(".generic").click(function(add_generic) {
if (generic_counter > 5) {
alert("You've been looking up a lot about GENERIC, maybe contact this group?")
} else {
generic_counter += 1;
console.log(generic_counter);
}
});
});

最佳答案

如果您使用 ==(或 ===)进行比较,并且始终增加计数器,则仅在第六次点击时出现警报。

注意:在ready 事件处理程序中声明变量,它不需要是全局变量。

// When button is clicked, add 1 to the variable
$(document).ready(function() {

// Declare the variable
var generic_counter = 0;
// Log the variable
console.log(generic_counter);

$(".generic").click(function() {
generic_counter++;
console.log(generic_counter);
if (generic_counter == 6) {
alert("You've been looking up a lot about GENERIC, maybe contact this group?");
}
});

});

如果不想继续计数,也可以在显示更改后使用 off 方法注销事件处理程序:

// When button is clicked, add 1 to the variable
$(document).ready(function() {

// Declare the variable
var generic_counter = 0;
// Log the variable
console.log(generic_counter);

$(".generic").click(function() {
generic_counter++;
console.log(generic_counter);
if (generic_counter == 6) {
alert("You've been looking up a lot about GENERIC, maybe contact this group?");
$(".generic").off('click');
}
});

});

对于更通用的解决方案,您可以制作一个插件:

$.fn.clickUntil(cnt, message) {
var elements = this;
return this.click(function(){
if (--cnt == 0) {
alert(message);
elements.off('click');
}
});
}

然后您可以轻松地为多个元素制作消息。示例:

$(document).ready(function() {
var items = [
{ selector: '.generic', name 'GENERIC' },
{ selector: '.super', name 'SuPeR' },
{ selector: '.mordor', name 'M0rd0r' }
];
$.each(items, function(i, o){
$(o.selector).clickUntil(6, 'You've been looking up a lot about ' + o.name + ', maybe contact this group?');
});
});

关于javascript - 达到 IF 条件后停止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28716485/

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