开发者

Handle elements after innerHTML or html(). Javascript

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜