javascript - JQuery Ajax 用 Jquery 函数替换项目

标签 javascript jquery ajax function replace

这是我的问题...

我使用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/

相关文章:

javascript - Angular ui sref 不适用于触摸事件

jquery - 如何将 div 的副本从当前位置动画化到右上角

jquery - Symfony2 : AJAX request : How to handle authentication when needed?

javascript - 输入字段值的动态总计(在输入之后、提交之前)

javascript - 如何在 Ektron 的所有页面上放置跟踪代码?

javascript - 使用 php 运行 Javascript 代码

javascript - 如何从这个唯一的字符分隔字符串中删除重复项?

javascript - 从请求响应创建 PDF 不适用于 axios 但适用于 native xhr

javascript - 如何使用 jQuery 淡出主 div 并淡入相应单击缩略图的内容

javascript - 具有固定页眉和页脚、固定宽度侧边栏和灵活内容的布局