javascript – “click”监听器多次执行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – “click”监听器多次执行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2357字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试创建使用ajax创建行的表.问题是,当我根据类名分配“click”监听器时,它会被多次调用
我的代码是
function fn_getAlertRules(parentRowId) {
$.ajax({
type: "GET",
url: anyURL,
contentType: "application/json",
dataType: "json"
}).done(function(data) {
// create row to add to parent table's row
var s_rulesHtmlString = '<tr><td colspan="3" class="rules-parent-tr"><table><tbody>';
$.each(data, function(i, name) {
s_rulesHtmlString += '<tr class="rule-tr">';
s_rulesHtmlString += '<td class="eventid-td">Rule ID:'+ name.RuleId+'<span>' + name.OccuredEventId + '</span></td>';
s_rulesHtmlString += '<td>' + name.Name + '</td><td>' + name.RuleDate + '</td>';
s_rulesHtmlString += '</tr>';
});
s_rulesHtmlString += '</tbody></table></td></tr>';
// add row below parent tr
$(parentRowId).parent().after(s_rulesHtmlString);
$(".rule-tr").on("click", "td", function(event) {
// this code blocks get executed multiple times
});
});
}
任何人都可以告诉我,为什么它被多次调用?
解决方法:
您在每个(循环)中绑定click事件,并且在执行循环时将事件绑定多次,这就是您重复单击事件的原因.您可以在ajax调用之前将click事件委托给要添加的元素的父元素或文档,并且事件将自动绑定到在done函数中添加的动态添加元素.您可以在here上阅读有关事件委派的更多信息
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers. 07001.
function fn_getAlertRules(parentRowId) {
$(document).on("click", ".rule-tr td", function(event) {
// this code blocks get executed multiple times
});
$.ajax({
type: "GET",
url: anyURL,
contentType: "application/json",
dataType: "json"
}).done(function(data) {
// create row to add to parent table's row
var s_rulesHtmlString = '<tr><td colspan="3" class="rules-parent-tr"><table><tbody>';
$.each(data, function(i, name) {
s_rulesHtmlString += '<tr class="rule-tr">';
s_rulesHtmlString += '<td class="eventid-td">Rule ID:'+ name.RuleId+'<span>' + name.OccuredEventId + '</span></td>';
s_rulesHtmlString += '<td>' + name.Name + '</td><td>' + name.RuleDate + '</td>';
s_rulesHtmlString += '</tr>';
});
s_rulesHtmlString += '</tbody></table></td></tr>';
// add row below parent tr
$(parentRowId).parent().after(s_rulesHtmlString);
});
}
内容总结
以上是互联网集市为您收集整理的javascript – “click”监听器多次执行全部内容,希望文章能够帮你解决javascript – “click”监听器多次执行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。