开发者

Handle elements after innerHTML or html(). Javascript

开发者 https://www.devze.com 2023-01-14 03:43 出处:网络
I\'m adding new element through html() function of jQuery. Then I want to handel it. Is it possible to do that in way you see here?

I'm adding new element through html() function of jQuery. Then I want to handel it. Is it possible to do that in way 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('hell开发者_开发问答o')
 });


You can use .live(), like this:

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

Or, run the bind after you create it, like this:

$("#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'); });
});


You can use .delegate() to handle elements that are dynamically added to the #playlist_header container.

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

Or just add the .click() handler when you create the element.

 $("#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's comment.          
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号