问题描述
我正在 [在 jsfiddle 中] 尝试使用创建的函数将新创建的 TextNode
附加到以下 HTML 中的 <p>
:
I was experimenting [in jsfiddle] w/a function created to append a newly created TextNode
to the <p>
in the HTML below:
<button onclick="addTextNode('YES! ');">YES!</button>
<button onclick="addTextNode('NO! ');">NO!</button>
<button onclick="addTextNode('WE CAN! ');">WE CAN!</button>
<hr />
<p id="p1">First line of paragraph.</p>
这也是我的 javascript:
Here is my javascript as well:
function addTextNode(text) {
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
这很好用.但是,当我试图通过从标记中删除行为来使我的 javascript不显眼"时,症结就会显现出来......
This works fine. However, the crux reveals itself when I attempt to make my javascript 'unobtrusive' by removing the behavior from the markup...
<button>YES!</button>
<button>NO!</button>
<button>WE CAN!</button>
<hr />
<p id="p1">First line of paragraph.</p>
然后利用循环将 addEventListener
附加到每个 元素,然后使用子
TextNode
调用 addTextNode
:
then utilizing a loop to attach addEventListener
to each <button>
element, which in turn uses the child TextNode
to call addTextNode
:
function addTextNode(text) {
var newtext = document.createTextNode(text),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
var btns = document.getElementsByTagName("button");
for(i = 0; i < btns.length; i++){
var button = btns[i];
button.addEventListener("click", addTextNode(button.innerHTML));
}
我的代码发生了两件奇怪的事情:
当 [jsfiddle's] Code Wrap 设置为 'no wrap -在头脑中,什么都没有发生.
Two strange things happen with my code:
When [jsfiddle's] Code Wrap is set to 'no wrap - in head', nothing happens.
但是,当 Code Wrap 设置为 'onLoad'、'onDomReady' 或 'no wrap - in body' 函数在点击之前运行,我得到 this.
However, When Code Wrap is set to 'onLoad', 'onDomReady' or 'no wrap - in body' the function runs before the click and I get this.
谁能告诉我我错过了什么?
Could someone tell me what I'm missing?
推荐答案
你的问题的根源在这里:
The root of your problem is here:
button.addEventListener("click", addTextNode(button.innerHTML))
您正在执行该函数,而不是将其传递给事件侦听器.相反,通过引用传递函数,然后获取函数内部的 innerHTML.
You're executing the function rather than passing it to the event listener. Instead, pass the function by reference, then get the innerHTML inside the function.
function addTextNode() {
var newtext = document.createTextNode(this.innerHTML),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
var btns = document.getElementsByTagName("button");
for(i = 0; i < btns.length; i++){
var button = btns[i];
button.addEventListener("click", addTextNode);
}
http://jsfiddle.net/bn85J/
这篇关于如果有的话,为什么 addEventListener 在事件之前触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!