这是我的问题...
我使用ajax和jquery来填写表格... 用户在选择中选择某些内容,并且当他选择了这个或那个时,ajax 返回数据,并将该数据放入表单中...
有时,新元素是通过ajax数据返回创建的,例如:
ajax 返回“blahblah”, 然后我把它放在我的表格中,如下所示:
$("#myDiv").empty();
$("#myDiv").html(ajaxReturn);
效果很好! 但是:
我的 jquery 不再观察到我放入表单中的新元素...! 我有一个这样的函数:
$("#xxxx").on("change",function(){
alert("something");
});
这个函数非常适合我在页面加载时表单中的元素, 一旦这个元素被我的 ajax 调用中的另一个元素替换,即使它与前一个元素具有相同的 ID,JQuery 也不会再发现其上的操作...
我该如何解决这个问题?
(我真的需要用我的ajax返回替换我的选择,因为有时它不再是一个选择,而是我需要的输入文本......)
感谢您的建议:)
最佳答案
事件处理程序仅绑定(bind)到当前选定的元素;当您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。
当您使用 ajax 替换元素时。
您需要使用Event Delegation使用.on()委托(delegate)事件方法。
使用
$("#myDiv").on('change', "#xxxx", function(){
//Your code
});
The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
关于javascript - JQuery Ajax 用 Jquery 函数替换项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698633/