Process elements after innerHTML or html (). Javascript

I am adding a new element through the html() jQuery function. Then I want to convey it. Is it possible to do as you see here?

  $("#renamePlaylist").click(function(){ var aa = '<input type="text" name="plst_name" value="'+$("#playlist_header").find("span").text()+'" size="'+Math.round($("#playlist_header").find("span").text().length/2)+'">'+ '<input id="renameCurrent" type="image" name="+" value="submit" alt="+">'; $("#playlist_header").find('span').html(aa); }); $("#renameCurrent").click(function(){ alert('hello') }); 
+4
source share
2 answers

You can use .live() , for example:

 $("#renameCurrent").live('click', function(){ alert('hello') }); 

Or run bind after creating it, for example:

 $("#renamePlaylist").click(function(){ var aa = '<input type="text" name="plst_name" value="'+$("#playlist_header").find("span").text()+'" size="'+Math.round($("#playlist_header").find("span").text().length/2)+'">'+ '<input id="renameCurrent" type="image" name="+" value="submit" alt="+">'; $("#playlist_header").find('span').html(aa); $("#renameCurrent").click(function(){ alert('hello'); }); }); 
+1
source

You can use .delegate() to process items dynamically added to the #playlist_header container.

 $("#playlist_header").delegate('#renameCurrent', 'click', function(){ alert('hello'); }); 

Or just add a .click() handler when creating the item.

  $("#renamePlaylist").click(function(){ var $aa = $('<input type="text" name="plst_name" value="'+$("#playlist_header").find("span").text()+'" size="'+Math.round($("#playlist_header").find("span").text().length/2)+'">'+ '<input id="renameCurrent" type="image" name="+" value="submit" alt="+">'); $aa.filter('#renameCurrent').click(function() { alert('hello'); }); $("#playlist_header span").html($aa); // Edit from @Nick comment. }); 
+1
source

All Articles