2010-09-03 45 views
4

我正在通過jQuery的html()函數添加新元素。然後我想要處理它。是否有可能以你在這裏看到的方式做到這一點?處理innerHTML或html()後的元素。 Javascript

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

你試過了嗎? – 2010-09-03 17:24:44

+0

是的:)不工作...... :( – Pol 2010-09-03 17:52:07

回答

1

您可以使用.live(),像這樣:

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

;或者執行綁定創建之後,像這樣:

$("#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

您可以使用.delegate()處理元素被動態添加到#playlist_header容器中。

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

或者只是在創建元素時添加.click()處理程序。

$("#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

第二個版本會增加一個點擊額外的元素:)也只是作爲一個提示,'.html($ aa)'是一個快捷方式;) – 2010-09-03 17:29:44

+0

@Nick - 確實它會。固定。 :o)雖然,我認爲'.html($ aa)'會導致'[object Object]'。編輯:不,我錯了。 – user113716 2010-09-03 17:30:50