我有这个代码
$(".generate").click(function() {
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").click(function() {
alert(data);
});
}
});
});
当单击“生成”按钮时,将调用 getJSON 函数,如果数据显示“确定”,那么我可以按“mybutton”来提醒数据;
唯一的问题是,如果我按“生成”按钮几次(我希望发生这种情况),“mybutton”也会多次提醒“hello”(取决于我单击生成按钮的次数) )。
我尝试过e.stopPropagation()
,但这没有帮助。
最佳答案
原因是每次单击按钮 .generate
时,都会在具有类 .mybutton
的元素上添加一个新的事件处理程序
目前还不清楚你想要做什么,但如果目的是存储从 ajax 调用中获取的数据,你可以这样做:
//data container
var localData;
//will show the actual content of the variable when .mybutton is clicked
$(".mybutton").click(function()
{
alert(localData);
});
//this will update the variable when .generate is clicked
$(".generate").click(function()
{
$.getJSON("jsonfile.json").done(function(data)
{
if (parseInt(data)>0)
{
localData = data;
//this will trigger the click event on the button .mybutton that will fire the handler with the alert
$(".mybutton").trigger('click');
}
});
});
关于javascript - 防止 jQuery 中的双重事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783210/