gpt4 book ai didi

javascript - 单击功能在动态创建的元素 Jquery 上无法按预期工作

转载 作者:行者123 更新时间:2023-12-03 05:13:42 25 4
gpt4 key购买 nike

我有动态创建的元素列表,单击这些元素会触发 ajax 请求并显示结果。问题是它只有在单击两次时才起作用。第一次点击元素不起作用。而第二次点击效果完美。我不明白这背后的原因。我确实尝试过unbind()但这没有帮助

$("#profiles_name ul a").on('click',function(event){
$.ajax({
}
});
});.

我确实尝试过$("#profiles_name ul a").unbind().on('click',function(event)..它仍然不起作用。

这是我动态创建的标签

<ul>
<a href="javascript:myfunction(this)" data-value="20/20"><li>Frontend Dev</li></a>
<li class="divider"></li>
</ul>

还要注意的是,例如,如果我有两个动态创建的列表,当我单击列表 1(第一次)时,它不起作用,列表 1(第二次)起作用。页面刷新后,单击列表 1(第一次)不起作用,单击列表 2(第一次)起作用。即,无论动态创建的元素如何,第一次单击都不起作用。

最佳答案

更喜欢使用event delegation :

$("#profiles_name").on('click', 'ul a', function() {
$.ajax({
// Your code here
});
});

Event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

关于javascript - 单击功能在动态创建的元素 Jquery 上无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41696650/

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