Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我的jQuery弹出插件按钮调用了错误的回调_Javascript_Jquery_Popup - Fatal编程技术网

Javascript 我的jQuery弹出插件按钮调用了错误的回调

Javascript 我的jQuery弹出插件按钮调用了错误的回调,javascript,jquery,popup,Javascript,Jquery,Popup,我创建了一个jQuery插件,它使用AJAX打开内部弹出窗口 调用弹出窗口时,我可以在弹出窗口底部设置操作按钮,并使用自定义回调 以下是生成按钮和设置回调的代码: for(i in settings.buttons) { var button = settings.buttons[i]; $('<a></a>', { text: button.label, href: '#', click: function(e){ e.prev

我创建了一个jQuery插件,它使用AJAX打开内部弹出窗口

调用弹出窗口时,我可以在弹出窗口底部设置操作按钮,并使用自定义回调

以下是生成按钮和设置回调的代码:

for(i in settings.buttons)
{
var button = settings.buttons[i];

$('<a></a>', {
    text: button.label,
    href: '#',
    click: function(e){
        e.preventDefault();
        button.callback.call();
    },
    'class': (typeof button.color == 'undefined' ? '' : button.color)
}).appendTo(popup.buttons);
}
for(设置中的i.按钮)
{
var按钮=设置。按钮[i];
$('', {
text:button.label,
href:“#”,
点击:功能(e){
e、 预防默认值();
button.callback.call();
},
'class':(typeof button.color=='undefined'?'':button.color)
}).appendTo(弹出式按钮);
}
问题是,代码调用了错误的回调,例如,如果我设置了两个按钮,其中一个触发弹出窗口关闭,而另一个复制了一些输入的值,任何按钮都会触发第二个回调


我应该如何修复它?

因为单击功能将在
for in
循环完成后执行
button.callback.call()将始终调用最后一个按钮回调

解决方案:保存上下文

 function keepContext(button) {
      $('<a></a>', {
        text : button.label,
        href : '#',
        click : function(e) {
            e.preventDefault();
            button.callback.call();
        },
        'class' : (typeof button.color == 'undefined' ? '' : button.color)
    }).appendTo(popup.buttons);    
}
for (i in settings.buttons) {
    keepContext(settings.buttons[i]);
}
函数keepContext(按钮){
$('', {
text:button.label,
href:“#”,
点击:功能(e){
e、 预防默认值();
button.callback.call();
},
'class':(typeof button.color=='undefined'?'':button.color)
}).appendTo(弹出式按钮);
}
用于(设置.按钮中的i){
keepContext(settings.buttons[i]);
}

你的回答对我很有帮助。非常感谢,我从没想过。我尝试了类似的方法(正如您所注意到的,设置了一个名为
按钮的varieble
),但没有任何效果。谢谢(: