Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Does anyone know why if you use document.body.innerHTML += "content"; the JavaScript on the page stops working? I have the following code:

document.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    try {
        document.getElementById('menu').remove();
    } catch (x) {
        //
    }
    var newHtmlText = "<div id='menu'>";
    newHtmlText += "<div class='menu-item' id='menu-back' onclick='window.history.back();'>" +
        "<div class='fa fa-arrow-left icon'></div><div class='text'>Back</div><div class='clear'></div></div>";
    newHtmlText += "<div class='menu-item' id='menu-forward' onclick='window.history.forward();'>" +
        "<div class='fa fa-arrow-right icon'></div><div class='text'>Forward</div><div class='clear'></div></div>";
    newHtmlText += "<div class='menu-item' id='menu-reload' onclick='location.reload();'>" +
        "<div class='fa fa-repeat icon'></div><div class='text'>Reload</div><div class='clear'></div></div>";
    newHtmlText += "<hr />";
    newHtmlText += "<div class='menu-item' id='menu-home' onclick='location.href = "/";'>" +
        "<div class='fa fa-home icon'></div><div class='text'>Home</div><div class='clear'></div></div>";
    newHtmlText += "</div>";
    document.body.innerHTML += newHtmlText;
    var menu = document.getElementById('menu');
    menu.style.left = (e.clientX) + "px";
    menu.style.top = (e.clientY) + "px";
});

Every time I open the context menu the JavaScript stopped working. This is not the only time it has done this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
411 views
Welcome To Ask or Share your Answers For Others

1 Answer

Using x.innerHTML += y is equivalent to x.innerHTML = x.innerHTML + y;

This means that you are completely overwriting the old document with a new document - it may appear visually the same, but under the hood you've just nuked every single reference to everything.

If a bit of JavaScript elsewhere in the page used something like var container = document.getElementById('container');, in order to save a reference, well that reference is now gone.

If there are any event listeners bound to elements in the document, those are gone too because the elements were nuked and replaced with identical-looking ones.

If you want to add your context menu to the page, you should do something like:

var menu = document.createElement('div');
menu.id = 'menu';
menu.innerHTML = "Your menu HTML here";
document.body.appendChild(menu);

This will add the new element to the page without nuking the whole thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...