模式弹出窗口无法正常工作,它多次调用函数 - 单击事件处理程序运行多次
Modal popup is not working properly, its calling a function multiple times - click event handler runs several times
这里是模态的JSP代码
<div class="modal hide fade" id="showDupZip">
<div class="modal-header portlet box bd-grey ">
<div class="portlet-title">
<button type="button" class="close" id="closeModal1" data-dismiss="modal" aria-hidden="true"></button>
</div>
</div>
<div class="modal-body">
<BUTTON class="btn login-blue"
id="yes" type="button" data-dismiss="modal">Yes</BUTTON>
<BUTTON class="btn login-blue"
id="cancel" type="button" data-dismiss="modal">Cancel</BUTTON>
</div>
</div>
这是java脚本代码
function showModal1(r1,r2,r3){
$('#showDupZip').removeClass('hide');
$('#showDupZip').modal({
backdrop : 'static',
keyboard : false
}).on('click', '#yes', function() {
$('#loading-overlay1').show();
$('#loading-message1').show();
checkMaxCount(r1,r2,r3);
}
});
}
function checkMaxCount(r1,r2,r3)
{
//some code here
}
因此,单击"是"按钮应该调用checkMaxCount((函数。
我说一个场景
假设这个弹出窗口来了,我单击了两次取消按钮,两次弹出窗口都关闭了,但第三次我单击了是按钮,然后 checkMaxCount(( 函数执行了三次。我在该功能中发出警报,警报来了三次。意味着每次模态出现时,它在单击"是"按钮后多次执行该函数。我不明白为什么会出现这个问题。checkMaxCount(( 函数应该只执行一次。
问题是您每次打开模态时都会订阅该事件。因此,它的处理次数与打开次数相同。
您应该订阅点击处理程序,即仅调用一次.on('click',...)
。为此,请将其移出showDialog
函数。(别担心,这是很多人都会犯的经典错误(。
如注释中所述,如果将事件注册移到函数之外,则无法再将r1, r2, r3
值传递给处理程序。为了能够在处理程序中使用这些值,您可以将它们提取到外部作用域中的变量中,以便可以从该作用域修改它们,并从处理程序的内部作用域进行访问:
// Define the vars in outer level
var r1,r2,r3;
$('#showDupZip').on('click', '#yes', function() {
$('#loading-overlay1').show();
$('#loading-message1').show();
// Use them here
checkMaxCount(r1,r2,r3);
}
function showModal1(){
$('#showDupZip').removeClass('hide');
$('#showDupZip').modal({
backdrop : 'static',
keyboard : false
});
});
通过此更改,您只需要在调用 show modal 之前设置 var,而不是将它们作为参数传递。
var r1=1; var r2=2; var r3=3;
showDialog();
当然,这是解释如何做到这一点的最简单方法。但是 ypu 应该给你的代码一个更好的结构,例如把它包含在里面和 IIFE 中,以避免污染全局上下文。
(function() {
var r1,r2,r3;
// The rest of the code here
}());
如果没有看到更多的代码,很难给你更好的建议。
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量