Why does addEventListener light up before the event, if at all?

I experimented in [jsfiddle] with a function created to add the newly created TextNodeto <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>

Here is my javascript:

    function addTextNode(text) {
        var newtext = document.createTextNode(text),
            p1 = document.getElementById("p1");

        p1.appendChild(newtext);
    }

It works great. However, crux detects itself when I try to make a "joblubive" of my javascript 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>

then using a loop to attach addEventListenerto each element <button>, which in turn uses a child TextNodeto 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));
    }

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

, Code Wrap 'onLoad', 'onDomReady' 'no wrap-in body', , this.

- , ?

+4
2

:

button.addEventListener("click", addTextNode(button.innerHTML))

, . , innerHTML .

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/

+8

-, Add Event. add event listener , , .

:

var myfunctionreference = addTextNode;

var myfunctioncall = addTextNode();

. . AddEventListener()

:

button.addEventListener("click", addTextNode);

-, . , , . "this" , .

function addTextNode(evt) {
    var newtext = document.createTextNode(this.innerHTML),
        p1 = document.getElementById("p1");

    p1.appendChild(newtext);
}
+1

Source: https://habr.com/ru/post/1541671/


All Articles