我正在尝试使用 jquery 将函数绑定(bind)到新添加的元素...我已经尝试了很多在线示例,但不知何故对我没有任何作用。我创建了一个带有 id 和一个按钮的表单,在提交时从另一个页面加载 ajax 元素并在当前网站上插入 html。一切似乎工作正常,但新加载的元素没有绑定(bind)任何事件。 这是 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 元素,可以绑定(bind)到 jQuery 函数。
最佳答案
基本上有两个选项可以做到这一点:
在附加新的 html 后绑定(bind)您的事件:
$(this).ajaxStop(function(){ $(this).after($(d).find(".edit-content").html()); // do you binding here });
使用事件委托(delegate)(使用 .on() 或 .delegate() )。
$('.some-container').on('click', '.edit-button', function(e) {...});
这会将点击事件委托(delegate)给具有类 .edit-button 的任何子元素的 .some-container,无论后者已经在 dom 中还是之后加载。
关于jquery - 将事件绑定(bind)到动态添加的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8805689/