我有这段代码
$(".generate").click(function() {
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").click(function() {
alert(data);
});
}
});
});
当"生成"单击按钮,调用getJSON函数,如果数据显示" ok"然后我可以按下" mybutton"提醒数据;
唯一的问题是如果我按下"生成"按钮几次(我希望这发生)," mybutton"会警告"你好"也是很多次(取决于我点击生成按钮的次数)。
我尝试了e.stopPropagation()
,但这没有帮助。
答案 0 :(得分:2)
原因是每次单击按钮.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');
}
});
});
答案 1 :(得分:1)
使用与on()类似的委托
$(function() {
var buttonData = {};
$(".generate").click(function() {
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data) > 0) {
buttonData = data;
}
});
});
$(document).on('click', '.mybutton', function() {
alert(buttonData);
});
});
并将其绑定到getJSON
成功处理程序
答案 2 :(得分:1)
如果你这样试试怎么办? (没有测试,但应该工作)
$(".generate").click(function() {
$(this).unbind('click').next()
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").click(function() {
$(this).unbind('click').next()
alert(data);
});
}
});
});
答案 3 :(得分:1)
为什么你总是重新加入这个事件。单击生成按钮后,是否从DOM中删除了按钮?
如果不是,你只能绑定事件一次,只是在没有数据时禁用按钮:
$(".mybutton").prop('disabled', true); // initially disable
$(".mybutton").click(function() { // bind the event once
alert(data);
});
$(".generate").click(function() {
$(".mybutton").prop('disabled', true); // disable if new data starts to generate
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").prop('disabled', false); // enable if everything is ok
}
});
});
答案 4 :(得分:0)
您可以每次取消绑定并重新绑定处理程序
if (parseInt(data)>0) {
$(".mybutton").off('click').click(function() {
alert(data);
});
}