Bootstrap 3 - 远程加载的模式创建重复的javascript事件 [英] Bootstrap 3 - Remotely loaded modal creates duplicate javascript events
问题描述
我有一个带有2个按钮的简单页面,每个按钮使用以下方法代码远程填充模态的内容
I have a simple page with 2 buttons which each populate the content of a modal remotely using the following method code
$("button").click( function(e) {
e.preventDefault();
var remoteLoc = $(this).attr('data-loc');
$("#myModal .modal-content").load(remoteLoc, function() {
$("#myModal").modal("show");
});
});
$('#myModal').on('hidden.bs.modal', function (e) {
$("#myModal .modal-content").empty();
});
加载内容的一个简单示例是:
A simple example of the content being loaded is this:
<div class="modal-body">
<a id="tomtest" href="#">Test link</a>
<p>dfghdfgh dfgh dfgh dfgh dfgh dfgh dfgh dfg h</p>
</div>
<script type="text/javascript">
$(document).on("click", "a#tomtest", function(e) {
e.preventDefault();
alert(123);
});
</script>
问题是,自从页面加载后,警报会自动打开模式。
The problem is that the alert fires as many times as I've opened the modal since the page loaded.
我该怎样做才能阻止这种情况发生?
What can I do to stop this happening?
编辑!!!
根据@paulitto的答案,我修改了代码,在模态内容中添加动态创建的链接。
Based on the answer from @paulitto I've amended the code to add a dynamically created link in the modal content.
<div class="modal-body">
<a id="tomAdder" href="#">Add alert link</a>
<p>dfghdfgh dfgh dfgh dfgh dfgh dfgh dfgh dfg h</p>
</div>
<script type="text/javascript">
$("a#tomAdder").on("click", function(e) {
e.preventDefault();
$('<a class="tomtest" href="#">Test link</a>').prependTo(".modal-body");
});
$(document).on("click","a.tomtest", function(e) {
e.preventDefault();
alert(123);
});
</script>
在这种情况下有任何想法吗?
Any ideas in this case?
推荐答案
通过使用委托事件aproach,如 $(document).on(click,a#tomtest,function(e){...});
您是尚未存在的元素的绑定处理程序,这样您每次打开新模态时都会将新处理程序附加到相同的链接。
By using delegated events aproach like $(document).on("click", "a#tomtest", function(e) {...});
you are binding handlers to elements that do not exist yet, this way you append new handlers to same link each time opening new modal.
附加以通常的方式只对现有链接进行的事件:
Attaching event in usual way whould do it for only existing link:
$("a#tomtest").on("click", function(e) {
e.preventDefault();
alert(123);
});
更新:
如果你仍然需要使用委托事件aproach,你应该能够在绑定新的点击处理程序之前取消绑定所有这样的委托点击处理程序:
if you still need to use delegated events aproach, you should be able to unbind all delegated click handlers like this, before binding new click handler:
$(document).off("click", "a#tomtest" );
这篇关于Bootstrap 3 - 远程加载的模式创建重复的javascript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!