我在网页上动态加载了模板,并且打算使用按钮的id
进行一些操作。我为模板上的所有按钮使用了相同的名称。然后,我使用Jquery委托在单击按钮时提醒id
。
但是问题在于,第一次单击按钮不会触发按钮单击事件,而对随后的单击有效。重新加载页面后,再次出现相同的问题。如何实际停止此操作。我在下面附加了Jquery代码。
$("table").on("click", "button",function(event) {
$("[name='DEL_BTN']").on('click',function(event){
event.stopPropagation();
alert(this.id)})
});
<!-- LAYOUT OPTIONS -->
<div class="container">
<table class="table shadow p-3 mb-5 bg-white rounded" id="TABLE_CONTAINER">
</table>
</div>
<thead class="thead-dark">
<tr>
<th scope="col">NAME</th>
<th scope="col">EMAIL</th>
<th scope="col">DOB</th>
<th scope="col">DEPT</th>
<th scope="col">GENDER</th>
<th scope="col">AGE</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{{#each ALL_RECORDS}}
<tr>
<td scope="row">{{this.name}}</td>
<td scope="row">{{this.eMail}}</td>
<td scope="row">{{this.DOB}}</td>
<td scope="row">{{this.dept}}</td>
<td scope="row">{{this.gender}}</td>
<td scope="row">{{this.age}}</td>
<th scope="row" style="text-align: center"><button class="btn btn-primary" type="button" name="EDIT_BTN" id="{{this._id}}">EDIT</button></th>
<th scope="row" style="text-align: center"><button class="btn btn-danger" type="button" name="DEL_BTN" id="{{this._id}}">DELETE</button></th>
</tr>
{{/each}}
</tbody>
也请您解释一下发生这种情况的原因。提前非常感谢您。
答案 0 :(得分:1)
之所以发生,是因为您如何将click事件监听器添加到按钮中。您正在将该事件添加到[第一次单击]的另一个处理程序中,因此,只有在您第一次单击后,其中带有警报处理程序($("[name='DEL_BTN']")
)的按钮单击才会被注册。
检查下面的评论。
$("table").on("click", "button", function(event) {
// Wen you click first time it will register the next click:
$("[name='DEL_BTN']").on('click',function(event){
// Then on the second click, this event is now defined,
// that's why it runs only after the first click
event.stopPropagation();
alert(this.id)})
});
});
因此,为了解决这个问题,您只需像下面这样就在第一个处理程序上声明一次:
$("table").on("click", "[name='DEL_BTN']", function(event) {
event.stopPropagation();
alert(this.id)})
});
Handlebars.js注意:请确保使用
handlebars
编译模板后声明此事件。