jQuery单击事件触发多次 [英] jQuery on click event firing multiple times
问题描述
我刚刚学习了如何使用方法 .on(),并使用它添加了一个事件处理程序添加到实时"添加的某些按钮(在DOM准备就绪之后).
I just learned how to use the method .on() and I use it to add an event handler to some buttons that are added "live" (after the DOM is ready).
$('#table').on("click", ".delete", function() {
//whatever
});
这似乎很好用,但是当我在代码中使用它时,两次触发click事件.它会触发更改选择器的次数,也就是说,我单击选择器中的一个名称,然后单击另一个名称,比如说3次,然后单击提到的按钮时,我会收到所有这3个名称的警报当时只有一个被选中.
This seems to work fine but when I use it in my code I get the click event fired twice. It fires as many times as I have changed the selector, that is, I click a name in the selector and then another and another, let's say 3 times, then when clicking the mentioned button I will get an alert with all those 3 names instead of only the one is selected at that time.
我无法在JsFiddle中复制它,因为整个过程相当大.所以,让我知道我还能添加些什么来使问题变得更好.
I haven't been able to replicate it in a JsFiddle as the whole thing is quite big. So let me know what else I can add to make the question better.
JS
$('#dataSelector').change(function() {
#more code
$('#table').on("click", ".delete", function() {
var data_name = $("#dataSelector option:selected").attr('name');
alert(data_name);
});
});
HTML
<div id="selectData">
<label>Select:</label>
<br>
<div class="">
<select id="dataSelector" class="form-control">
<option id="default" selected="true" name="default">Pick</option>
<option value="1" name="somethingA">somethingA</option>
<option value="2" name="somethingB">somethingB</option>
<option value="3" name="somethingC">somethingC</option>
</select>
</div>
</div>
<div id="goal_table" class="col-md-12">
<table id="table" class="table table-bordered">
<tbody>
<tr>
<th>Name1</th>
<th>Name2</th>
<th>Name3</th>
<th>name4</th>
<th></th>
</tr>
<tr id="13">
<td>somethingA</td>
<td>value</td>
<td>whatever</td>
<td>∞</td>
<td>
<button name="13" type="button" class="btn btn-default delete"><i class="fa fa-trash" aria-hidden="true"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
推荐答案
只需在on()之前添加off()即可删除其上的现有事件
just add off() before on() to remove existing event on it
很有可能您已经在该元素中绑定了一个事件,因此,如果您想重新绑定该事件,则只需关闭('event')即可避免多次触发该事件
there's a possibility that you already bind an event in that element so if you want to rebind the event you just off('event') to avoid firing event multiple times
$('#table').off("click").on("click", ".delete", function() {
var data_name = $("#dataSelector option:selected").attr('name');
alert(data_name);
});
这篇关于jQuery单击事件触发多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!