2016-12-02 62 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); 
} 
相关问题