两个jquery点击计数器在点击处理程序之外协同工作



在下面的jQuery中,如果单击button1,我尝试在计数器上计数+1,如果单击按钮2,我尝试计数-1。

在我最初的项目中,计数器会用这个数字替换JSON rest API地址,搜索会跳到点击次数。

var counter = 1; 
$("#button1").click(function (e) { 
e.preventDefault();
counter += 1
});
$("#button2").click(function (e) { 
e.preventDefault();
counter -= 1;
});
console.log(counter)

您的代码正在中工作

console.log应该在函数内,您可以使用以下内容:

function updated(val){
console.log(val);
}
var counter = 1; 
$("#button1").click(function (e) { 
e.preventDefault();
counter += 1;
// You can use console.log(counter) here, or pass the value to another function
updated(counter);
});
$("#button2").click(function (e) { 
e.preventDefault();
counter -= 1;
updated(counter);
});

最新更新