Event Listener does not work

Any ideas why this is not working.

The "Yes" button works once when pressed - the "No" button does not work

function $(x) {
    return document.getElementById(x);
}

var glob = 0;

function new_index() {
    glob += 1;
    return "d" + glob;
}

function play() {
    say("Hello is JS Fun?");
    response("No",
        function() {
            say("Oh dear")
        });
    response("Yes",
        function() {
            say("Great:");
        });
}

function say(x) {
    $("txt").innerHTML += x;
}

function response(Txt, Fun) {
    var n = new_index();
    var s = "<button id='" + n + "'>" + Txt + "</button>";
    say(s);
    var xx = $(n);
    // xx.onclick=Fun;
    xx.addEventListener("click", Fun);
}

play();
<div id="txt"></div>
Run codeHide result
+4
source share
3 answers

This is because every time you set innerHTML, it doesn’t just add what you might think, it sets innerHTML to a new value and thus removes old elements with old event listeners attached.

+8
source

, , innerHTML - , . , .

DOM , HTML ( innerHTML). , (1) , (2) . createElement .

function $(x) {
    return document.getElementById(x);
}

var glob = 0;

function new_index() {
    glob += 1;
    return "d" + glob;
}

function play() {
    say(text("Hello is JS Fun?"));
    response("No",
        function() {
            say(text("Oh dear"));
        });
    response("Yes",
        function() {
            say(text("Great:"));
        });
}

function text(String) {
    var node = document.createElement("span");
    node.innerHTML = String;
    return node;
}

function say(x) {
    $("content").appendChild(x);
}

function response(Txt, Fun) {
    var button = document.createElement("button");
    button.innerHTML = Txt;
    button.addEventListener("click", Fun);
    say(button);
}

play();
<div id="content"></div>
Hide result
+2

Event handlers get lost on $("txt").innerHTML += x;.

+1
source

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


All Articles