2017-01-27 43 views
1

我試圖追加一個onclick事件,但是它不工作。它工作正常HTML中雖然附加Onlclick事件不起作用

var a = $("#testappendid").append('<div id="imagewrap"><a href="" id="infobutton" onclick="alert("test");"></a></div>'); 

var b = $("#testappendid").append('<div id="imagewrap"><a href="" id="infobutton" onclick="RedirectInformation();"></a></div>'); 

function RedirectInformation() { 
alert("test"); 
    } 
+0

爲什麼你追加具有相同ID的元素? –

回答

0

可以綁定click事件處理程序的元素使用.on方法添加dynamically

$(document).on('click','#infobutton',function(){ 
    //code here. 
}); 

瞭解更多關於event delegation

此外,您已嘗試爲兩個元素指定相同的id,這是錯誤的方法:id屬性必須是唯一的。