繁体   English   中英

带有JavaScript回调的jQuery Click事件被执行多次整理

[英]Jquery Click event with javascript callback is gertting executed more than one time

  function MyConfirm(message, callback) { console.log("In My Confirm"); var ids = document.getElementById("mymodal"); $('#MyText').html(message); ids.style.display = "block" $('input[id^=cfrm_]').click(function (e) { e.preventDefault(); console.log("In Click Event"); if (typeof callback === 'function') { callback($(this).attr('value')); } ids.style.display = "none" }); } var as="My Test Message"; function mytest(){ var na = MyConfirm(as, function (result) { console.log("Result: "+result) }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form id="form1" runat="server"> <div> <input id="Button1" type="button" onclick="mytest()" value="button" /></div> <div id="mymodal" style="display:none"> <div id="MyText"></div> <input id="cfrm_btnYes" type="button" value="Yes" /> <input id="cfrm_btnNo" type="button" value="No" /> </div> </form> </body> </html> 

我正在使用上面的代码来模仿默认的确认对话框窗口动作。 该功能运行正常。 但是在单击按钮后,将调用mytest(),它使div #mymodal与两个按钮一样可见。 但是,当您单击“是”或“否”按钮时,它会使div隐藏,但会多次遍历MyConfirm函数。 可以在控制台中看到。 谁能解释一下为什么我得到这个奇怪的答复。 我的目标是为confirm()fn创建一个替代项。 具有返回值。

请尝试return 也许准备好了。

问题在于, 每次执行MyConfirm()函数时,都绑定一个新的click事件以确认按钮。 click事件绑定不会覆盖旧的绑定,但会向该事件添加新功能。

您可以添加$('input[id^=cfrm_]').off('click'); 在绑定新绑定之前删除旧绑定。

 function MyConfirm(message, callback) { console.log("In My Confirm"); var ids = document.getElementById("mymodal"); $('#MyText').html(message); ids.style.display = "block" $('input[id^=cfrm_]').off('click'); $('input[id^=cfrm_]').click(function (e) { e.preventDefault(); console.log("In Click Event"); if (typeof callback === 'function') { callback($(this).attr('value')); } ids.style.display = "none" }); } var as="My Test Message"; function mytest(){ var na = MyConfirm(as, function (result) { console.log("Result: "+result) }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form id="form1" runat="server"> <div> <input id="Button1" type="button" onclick="mytest()" value="button" /></div> <div id="mymodal" style="display:none"> <div id="MyText"></div> <input id="cfrm_btnYes" type="button" value="Yes" /> <input id="cfrm_btnNo" type="button" value="No" /> </div> </form> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM