【发布时间】:2016-12-02 10:37:44
【问题描述】:
我在页面上动态创建和删除元素“a”和“button”。我想在创建它们时向它们添加处理程序“onclick”。到目前为止,我看到的所有示例都在 jquery 中。我怎样才能在纯javascript中做到这一点?
【问题讨论】:
-
这是 vanilla js 的文档:w3schools.com/js/js_htmldom_eventlistener.asp
标签: javascript
我在页面上动态创建和删除元素“a”和“button”。我想在创建它们时向它们添加处理程序“onclick”。到目前为止,我看到的所有示例都在 jquery 中。我怎样才能在纯javascript中做到这一点?
【问题讨论】:
标签: javascript
你可以这样做:
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);
}
【讨论】:
您可以使用addEventListener 在动态按钮上添加点击监听器。
var btn = document.createElement("button");
btn.addEventListener('click', function(){
alert('button clicked!');
}, false);
document.body.appendChild(btn);
【讨论】:
本示例将创建一个带有一些文本的按钮并将其添加到 id 为 test 的元素中。
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('test'));
btn.addEventListener('click', function() {
alert('it works');
}, false);
document.getElementById('test').appendChild(btn);
希望对你有所帮助。
【讨论】:
来自: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);
【讨论】: