Handle click event for appended elements in jQuery

半腔热情 提交于 2019-11-30 04:39:41

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!");
}); 

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/

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!