This question already has answers here:
Event binding on dynamically created elements?
                                
                                    (23个答案)
                                
                        
                2年前关闭。
            
        

我正在动态添加一些代码(!包括js代码!)。

<div class="r"></div>
<script>
    //Here is code that dinamiccaly add another div into div.r
    //Example:
    //<div class="w"><img src="a.png"><div class="i">Some Text</div></div>
    $('.r').on('click', $('.w'), function (e) {
        console.log($(this).children($('.i')).text());
    });
</script>


我在div.w中单击后,此click事件仍然起作用的问题,并返回所有div.w的文本,这些文本组合在一个字符串中,不带空格(sometext1sometext2)。

对不起,如果我写错了。我英语不好。

最佳答案

事件委托是错误的。您正在使用jQuery集合

$('.r').on('click', $('.w'), function (e) {
                    ^^^^^^^


它应该只是一个选择器

$('.r').on('click', '.w', function (e) {
                    ^^^^

关于javascript - 点击时的jQuery不适用于动态添加的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50880271/

10-13 00:13