我正在尝试使用 jquery 将函数绑定到新添加的元素...我已经尝试了很多在线示例,但不知怎的,没有任何效果对我有用。我创建了一个带有 id 和一个按钮的表单,在提交 ajax 时从另一个页面加载元素并在当前网站上插入 html。一切似乎都工作正常,但新加载的元素没有绑定任何事件。
这是 HTML:
<form id="tclick" method="post" action="${tg.url('/entryCmd')}">
<input type="hidden" name="id" value="${entries[0].id}" />
<input type="submit" value="submit"/>
</form>
和 jQuery:
$("#tclick").on("submit", function(data){
var h = $(this).serialize();
var d;
$.get($(this).attr("action"), h,
function(returnData) {
d = returnData;
}
);
$(this).ajaxStop(function(){
$(this).after($(d).find(".edit-content").html());
});
return false;
});
edit-content div 在表单元素之后立即加载。它有一些 a 元素,应该绑定到 jQuery 函数。
基本上有两种选择来做到这一点:
-
添加新的 html 后绑定您的事件:
$(this).ajaxStop(function(){
$(this).after($(d).find(".edit-content").html());
// do you binding here
});
-
使用事件委托(与.on() http://api.jquery.com/on/ or 。代表() http://api.jquery.com/delegate/).
$('.some-container').on('click', '.edit-button', function(e) {...});
这会将点击事件委托给任何具有 .edit-button 类的子元素的 .some-container 元素,无论后者已经在 dom 中还是之后加载。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)