弹窗中包含按钮的,按钮一般都需要绑定事件。
这个时候就会有一个常犯的错误,那就是按钮的事件会被多次绑定,导致按钮的事件执行次数,随着弹窗弹出的次数累加。
分析一下如下代码:
function showWin(win){
win.show();
win.find('a.btn').click(function(e){
alert('clicked');
})
};
a.btn 每次都会被绑定一个匿名函数。这导致下一次弹出的时候,a.btn 仍然会被绑定新的匿名函数,虽然看起来他们的功能是一样的。
这样弹出N多次之后,就形成了如下形式
a.click([fn1,fn2,fn3,fn4....fnN]);
正确的写法如下:
function showWin(win){
win.show();
win.find('a.btn').unbind('click').click(function(e){
alert('clicked');
})
};
如果是live的话,请用die 解除绑定:
function showWin(win){
win.show();
win.find('a.btn').die('click').live(function(e){
alert('clicked');
})
};