本文介绍了为什么addEventListener在事件发生之前呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试[在jsfiddle]中创建一个函数,以将新创建​​的 TextNode 添加到< p> 在下面的HTML中:

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 附加到每个< button> 元素,它们又使用子 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的] 设置为没有包裹在头,没有任何反应。

Two strange things happen with my code:
When [jsfiddle's] Code Wrap is set to 'no wrap - in head', nothing happens.

但是,当被设置为'onLoad','onDomReady'或'没有换行 - 身体'功能在点击之前运行,我得到。

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?

推荐答案

您的问题的根源在于:

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);
}

这篇关于为什么addEventListener在事件发生之前呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 13:37