今天碰到了這樣一個問題,我在javascript中動態創建了一個button,
然后我想給改button添加click事件,綁定的function想要傳入一個變量參數,
一開始我想直接通過函數傳參傳進來,然而不知道為什么,click事件無法正常響應,
最后發現可以這么做,將需要傳入的參數加入button的屬性中,然后通過getAttribute()獲得:
1 function add_book_panel(infor){ 2 //在這個函數中進行DOM元素操作,需要傳入參數infor 3 … 4 var button = document.createElement("button"); 5 button.setAttribute("infor",infor); 6 button.addEventListener("click", function(){ 7 document.getElementById("id").innerText = this.getAttribute('infor'); 8 }); 9 … 10 }