Handle click event for appended elements in jQuery

2019-02-03 01:49发布

问题:

I have generated few elements in my page using following method. For example,

$("#button"+caption).click(function(){
        var firstDisplay = '<div id="firstDisp'+caption+'"><ul>';
        for(var i=0;i<parents.length;i++){
            firstDisplay=firstDisplay+'<li class="fClick">'+parents[i]+'</li>';
        }
        firstDisplay=firstDisplay+'</ul></div>';
        $(firstDisplay).dialog();
});

and when i create an onclick event for 'fClass' like so :

$(".fClick").click(function(){
    alert("hey!");
}); 

It does not works ! However, if i put the onclick function inside the other function, right after .dialog(), it works ! I have a lot of elements created this way, so I cannot put all onclick events in a single method. Is there any way around this? I am having the same problem with .append method as well.

回答1:

Change it to .on or .delegate based on the version of jQuery you are using..

As of jQuery 1.7+

$(document).on('click', '.fClick', function(){ 
    alert("hey!");
}); 

For older jQuery versions use delegate

$(document).delegate('.fClick', 'click', function(){
    alert("hey!");
}); 


回答2:

Use on instead of click:

$(".fClick").on('click',function(){
  alert("hey!");
}); 

click adds click handlers to .fClick elements that are present when you call $('.fClick').click({...}). New .fClick elements added later won't have the click event. But when you use on, all .fClick elements will have a click handler, even if they are added later.
Read more here: http://api.jquery.com/on/



回答3:

call the $(document).ready(function() again and add your code there. The document gets read (refreshed) again and you can just apply your code there.



回答4:

What Vega has said is completely working. There is a hint : I think in the second line there is a mistake. Probably you can use addClass method because you can't put id or class in rendering. Here is an example:

var content = "<div>Hello, World</div>";
$("div").after(content);
$("last:div").addClass("mydiv");

And the class will be added but I am not sure that you can add an id.