我有动态创建的元素列表,单击这些元素会触发 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/