gpt4 book ai didi

javascript - 附加动态内容后 onclick 不起作用

转载 作者:行者123 更新时间:2023-11-28 14:38:05 25 4
gpt4 key购买 nike

<div class="demo_restaurant">
<li class="school" onclick="dropdown(this)">
<span class="icon glyphicon glyphicon-education">
</span>
<span id="1" class="school_title item_title">ABC
</span>
</li>
<li class="school" onclick="dropdown(this)">
<span class="icon glyphicon glyphicon-education">
</span>
<span id="2" class="school_title item_title">WXY
</span>
</li>
</div>

当有人使用以下代码点击该 li 时,我试图获取 li id 值:

  $(".demo_restaurant li span").on("click", function (argument) {
alert($(this).attr('id'));
});

但问题是当我在 ajax 调用后添加更多 li 时。然后 li onclick 不起作用。在该附加元素中,尽管单击函数存在于 HTML 中,但它无法调用该函数。我怎样才能让它发挥作用?

最佳答案

试试这个:

  $('.demo_restaurant').on('click', 'li span', function(argument) {
alert($(this).attr('id'));
});

说明:

When elements are added to the DOM dynamically, you need to tell jQuery to listen for events on the closest parent that was there when your handler was bound. (Note that it would also work with any further parent, up to document, but it is considerably less optimal.)

另一种方法是每次添加一些新内容时将处理程序绑定(bind)到添加的 DOM。

关于javascript - 附加动态内容后 onclick 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49217997/

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