gpt4 book ai didi

javascript - jquery 选择器在由 ajax 加载时找不到元素

转载 作者:搜寻专家 更新时间:2023-11-01 04:54:24 24 4
gpt4 key购买 nike

没有一个 jQuery 选择器通过 Ajax 请求处理从服务器加载的元素,但它在正常模式下工作良好。

$('#myid').change(function(){
alert('OK!');
});

<select id="myid" >
<option>1</option>
</select>

如何解决这个问题?

最佳答案

事件处理程序只绑定(bind)到当前选中的元素;在您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

当您通过 ajax 加载内容时。

您需要使用 Event Delegation .你必须使用 .on()使用委托(delegate)事件方法。

使用

$(document).on('change','#myid', function(){
alert('OK!');
});

理想情况下,您应该将 document 替换为最接近的静态容器。

关于javascript - jquery 选择器在由 ajax 加载时找不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com