Javascript 如何从javascript覆盖html元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2487290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:35:57  来源:igfitidea点击:

How to overwrite html element from javascript?

javascripthtmldom

提问by Rella

I have HTML page with some HTML element with ID="logo". I need to create JS script (with no external libs calls) that will overwrite that html element with other HTML element like "<div id=logo> stuff inside </div>".

我有一些带有 .html 元素的 HTML 页面ID="logo"。我需要创建 JS 脚本(没有外部库调用),它将用其他 HTML 元素(如"<div id=logo> stuff inside </div>".

回答by T.J. Crowder

Most of the time, it's just the content you want to replace, not the element itself. If you actually replace the element, you'll find that event handlers attached to it are no longer attached (because they were attached to the old one).

大多数时候,它只是你想要替换的内容,而不是元素本身。如果您真的替换了该元素,您会发现附加到它的事件处理程序不再附加(因为它们附加到旧的)。

Replacing its content

替换其内容

Replacing the element's contentis easy:

替换元素的内容很容易:

var element;
element = document.getElementById("logo");
if (element) {
    element.innerHTML = "-new content-";
}

The innerHTMLproperty has only recently been standardized, but is supported by all major browsers (probably most minor ones, too). (See notes below about innerHTMLand alternatives.)

innerHTML属性最近才被标准化,但所有主要浏览器都支持(也可能是大多数次要浏览器)。(请参阅下面的注释innerHTML和替代方案。)

Replacing the element iself

替换元素本身

Actually replacingthe element itself is a little harder, but not much:

实际上替换元素本身有点困难,但不是很多:

var element, newElement, parent;

// Get the original element
element = document.getElementById("logo");

// Assuming it exists...
if (element) {
    // Get its parent
    parent = element.parentNode;

    // Create the new element
    newElement = document.createElement('div');

    // Set its ID and content
    newElement.id = "logo";
    newElement.innerHTML = "-new content here-";

    // Insert the new one in front of the old one (this temporarily
    // creates an invalid DOM tree [two elements with the same ID],
    // but that's harmless because we're about to fix that).
    parent.insertBefore(newElement, element);

    // Remove the original
    parent.removeChild(element);
}

Notes on innerHTMLand other DOM manipulation techiques

innerHTML和其他 DOM 操作技术的注意事项

There are a number of wrinkles around using innerHTMLin certain browsers, mostly around tables and forms. If you can possibly use a library like jQuery, Prototype, etc., I'd do so, as they've got workarounds for those issues built-in.

innerHTML在某些浏览器中使用存在许多问题,主要是围绕表格和表单。如果您可以使用jQueryPrototype等库,我会这样做,因为它们内置了解决这些问题的方法。

Alternatively, you can use the various other DOM methodsrather than innerHTML(the same ones I used for creating the div and adding/removing, above). Note that in most browsers, doing any significant amount of markup by doing a bunch of createElement, appendChild, etc., calls rather than using innerHTMLwill be dramaticallyslower. Parsing HTML into their internal structures and displaying it is fundamentally what browsers do, and so they're highly optimized to do that. When you go through the DOM interface, you're going through a layer built on top of their internal structures and not getting the advantage of their optimizations. Sometimes you have to do it that way, but mostly, innerHTMLis your friend.

或者,您可以使用其他各种DOM 方法而不是innerHTML(我在上面用于创建 div 和添加/删除的方法)。请注意,在大多数浏览器中,通过做一堆做标记的任何显著量createElementappendChild等等,呼叫,而不是使用innerHTML显着慢。将 HTML 解析为它们的内部结构并显示它是浏览器的基本工作,因此它们经过高度优化才能做到这一点。当您浏览 DOM 界面时,您将浏览一个构建在其内部结构之上的层,而没有获得其优化的优势。有时你必须这样做,但大多数情况下,innerHTML是你的朋友。

回答by Gordon Gustafson

Do you really need to 'replace' the element or can you just toggle its visibility? This is a technique that's much simpler and will be more efficient. Most importantly it keeps the content (html) separated from the behavior (javascript).

你真的需要“替换”元素还是你可以切换它的可见性?这是一种更简单、更高效的技术。最重要的是,它将内容 (html) 与行为 (javascript) 分开。

function toggle() {
    document.getElementById("logo").style.display="none";
    document.getElementById("element_to_show").style.display="block";
}

see T.J.'s answerif you actually want to replace the element.

如果您真的想替换元素,请参阅TJ 的回答