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.
});
精彩评论