2016-12-02 63 views
-1

我在頁面上動態創建和刪除元素「a」和「按鈕」。我想在創建它們時向它們添加處理程序「onclick」。到目前爲止,我見過的所有例子都在jQuery中。我怎麼能在純JavaScript中做到這一點?將「onclick」處理程序添加到純javascript中的動態創建元素

+1

這是香草的JS文檔:HTTP ://www.w3schools.co m/js/js_htmldom_eventlistener.asp – Fefux

+1

看到這篇文章:http://stackoverflow.com/questions/6956258/adding-onclick-event-to-dynamically-added-button –

回答

0

您可以使用addEventListener在動態按鈕上添加點擊偵聽器。

var btn = document.createElement("button"); 
btn.addEventListener('click', function(){ 
    alert('button clicked!'); 
}, false); 
document.body.appendChild(btn); 
+0

爲什麼不「onclick」? – Kooooro

+0

要了解更多關於代表團,請查看這個答案http://stackoverflow.com/a/6348597/823369 –

0

這個例子將創建一個按鈕,文本並與test的ID添加到一個元素。

var btn = document.createElement('button'); 
btn.appendChild(document.createTextNode('test')); 

btn.addEventListener('click', function() { 
    alert('it works'); 
}, false); 

document.getElementById('test').appendChild(btn); 

希望這會幫助你。

0

來自:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

HTML內容

<table id="outside"> 
    <tr><td id="t1">one</td></tr> 
    <tr><td id="t2">two</td></tr> 
</table> 

JavaScript內容

// Function to change the content of t2 
function modifyText() { 
    var t2 = document.getElementById("t2"); 
    if (t2.firstChild.nodeValue == "three") { 
    t2.firstChild.nodeValue = "two"; 
    } else { 
    t2.firstChild.nodeValue = "three"; 
    } 
} 

// add event listener to table 
var el = document.getElementById("outside"); 
el.addEventListener("click", modifyText, false); 
3

你可以這樣做:

for(var i=0;i<5;i++){ 
    var a = document.createElement("a"); 
    a.innerHTML="a"+i; 
    document.body.appendChild(a); 
    var button = document.createElement("button"); 
    button.innerHTML="button"+i; 
    button.onclick = function(){ 
    console.log("event on button"); 
    } 
    document.body.appendChild(button); 
} 
相關問題