This question already has answers here:
Event binding on dynamically created elements?
                                
                                    (23个答案)
                                
                        
                                5年前关闭。
            
                    
我有以下代码,您可以在http://jsfiddle.net/XBfMV/29/上对其进行测试

的HTML:

<div class="sam">div 1</div>
<div class="sam">div 2</div>
<div class="sam">div 3</div>
<div class="sam">div 4</div>


CSS:

.expanded{
    border-style:solid;
    border-width:1px;
    border-color:black;
    background-color:yellow;
    min-height:50px;
}


javascript:

$('.sam').on('click',function(){

    if ( $(this).hasClass('expanded') ){
        $(this).removeClass('expanded');
    } else {
        $(this).addClass('expanded');

    }

});

$(document).ready(function(){
    //Im just test to write some divs after document ready
    var output = '<div class="sam">div 5</div>';
    $(output).insertAfter('.sam:last').fadeIn('slow');
    var output = '<div class="sam">div 6</div>';
    $(output).insertAfter('.sam:last').fadeIn('slow');
});


运行后,当单击div1,div2,div3和div 4时,它将.expanded类添加/删除到div中,但是当单击java生成并打印到文档的div5和div6时,它将不会添加/删除当我单击它们时,从他们那里上课。

有什么解决办法吗?

最佳答案

将选择器添加到on函数。

写:

$(document).on('click', '.sam', function () {
    if ($(this).hasClass('expanded')) {
        $(this).removeClass('expanded');
    } else {
        $(this).addClass('expanded');
    }
});


Updated fiddle here.

Refer syntax.

10-05 20:54
查看更多