admin管理员组文章数量:1435859
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.
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.
Share Improve this question edited Jul 22, 2017 at 17:58 Makyen♦ 33.4k12 gold badges92 silver badges125 bronze badges asked Jul 20, 2017 at 12:38 PetePete 3331 silver badge14 bronze badges 11-
There's no
jquery
code here. Maybe you meantjavascript
. – abhishekkannojia Commented Jul 20, 2017 at 12:39 - Instead of this document.body.innerHTML += elem; use $('body').append(elem); ... since you are using jQuery. – Shiladitya Commented Jul 20, 2017 at 12:40
-
It should be
document.body.innerHTML = elem
. You need to remove the+
sign. – Milan Chheda Commented Jul 20, 2017 at 12:40 - 1 The other place I am using it is on a chrome extension, so I don't know if the user has jQuery or not. – Pete Commented Jul 20, 2017 at 12:40
- If you're using it in a chrome extension I'd suggest you e up with a more unique id than "menu" – Khauri Commented Jul 20, 2017 at 12:41
3 Answers
Reset to default 5Using x.innerHTML += y
is equivalent to x.innerHTML = x.innerHTML + y;
This means that you are pletely 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.
document.body.innerHTML += "content";
Does three things:
- Reads the value of
innerHTML
- Modifies that value
- Overwrites
innerHTML
with the new value
This deletes the page and then creates a new one.
Since script elements inserted with innerHTML
are not executed, this kills the JS.
Don't append data using innerHTML
. Generate DOM nodes (with createElement
, createTextNode
and friends) and then append them (with appendChild
, insertBefore
and so on).
As has been explained by others, using:
document.body.innerHTML += newHtmlText;
deletes the entire page and recreates it. This causes:
- All event listeners which were placed on elements to bee disconnected from the DOM. If there is not some external reference to the DOM element or the listener function (e.g. a named function), the listener will be garbage collected (browser dependent).
- Any saved references to elements will now reference elements which are no longer in the DOM. These DOM nodes, and their children, will not be garbage collected, as there is still a reference to them. The JavaScript using these references will not throw errors unless it tries to find references to associated DOM nodes to which the element is no longer connected (ancestor nodes, e.g.
.parentNode
). However, the JavaScript will be pletely ineffective at manipulating the displayed DOM, as it will be using references to elements which are no longer in the DOM. - The entirety of the old DOM will be garbage collected (browser dependent), except for any elements, and their children, which have a reference saved elsewhere in JavaScript code.
This will almost certainly pletely break most already existing JavaScript.
Use .insertAdjacentHTML()
The correct way to add HTML text, without disturbing the already existing contents, is to use element.insertAdjacentHTML(relativeLocation, HTMLtext)
. Using .insertAdjacentHTML()
, you can add HTML text in four different locations relative to the referenced element. The value of relativeLocation
can be:
'beforebegin'
: Prior to the element'afterbegin'
: Just inside the beginning of element (like adding a new.firstChild
, but you can add as many children (as much HTML text) as you desire).'beforeend'
: Prior to the end of the element (like.appendChild()
, but you can add as many children (as much HTML text) as you desire).'afterend'
: Just after the element (likeelement.parentNode.insertBefore(newElement,element.nextSibling)
, but you can add as many children of the parentNode (as much HTML text) as you desire). Note: If you were inserting an element you could also use:element.insertAdjacentElement('afterend',newElement)
.
For what you desire to do, you would use:
document.body.insertAdjacentHTML('beforeend',newHtmlText);
本文标签: htmlInpage JavaScript stops when I use documentbodyinnerHTMLnewHtmlTextStack Overflow
版权声明:本文标题:html - In-page JavaScript stops when I use document.body.innerHTML += newHtmlText - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745668000a2669398.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论