Javascript 如何用javascript中的另一个div替换div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37347690/
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 20:13:43  来源:igfitidea点击:

How to replace div with another div in javascript?

javascripthtml

提问by DiPix

How to replace div with another div in javascript?

如何用javascript中的另一个div替换div?

This is what I have:

这就是我所拥有的:

<div id="main_place">
main
</div>

<button onclick="show(operation1)">Replace to operation 1</button>
<button onclick="show(operation2)">Replace to operation 2</button>
<button onclick="show(operation3)">Replace to operation 3</button>


<div id=operation1 style=“display:none”>
Some textboxes and text
</div>

<div id=operation2 style=“display:none”>
Again some textboxes and text
</div>

<div id=operation3 style=“display:none”>
And again some textboxes and text
</div>

<script>
function show(param_div_id){
        document.getElementById('main_place').innerHTML = Here should be div from param;
        }
</script>

Is it even possible to do it without jquery?

甚至可以在没有 jquery 的情况下做到这一点吗?

回答by Lee.Winter

Pass strings into your method and get the other div

将字符串传递到您的方法中并获取另一个 div

<div id="main_place">
  main
</div>

<button onclick="show('operation1')">Replace to operation 1</button>
<button onclick="show('operation2')">Replace to operation 2</button>
<button onclick="show('operation3')">Replace to operation 3</button>


<div id=operation1 style=“display:none”>
  Some textboxes and text
</div>

<div id=operation2 style=“display:none”>
  Again some textboxes and text
</div>

<div id=operation3 style=“display:none”>
  And again some textboxes and text
</div>

<script>
  function show(param_div_id) {
    document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).innerHTML;
  }
</script>

回答by ndugger

2019 Update:

2019 更新:

child.replaceWith(newElement);

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith

In the specific case of this question, I would recommend using replaceWithwith a clone of the node OP wishes to swap in. This could look like:

在此问题的特定情况下,我建议使用replaceWithOP 希望交换的节点的克隆。这可能如下所示:

const main = document.getElementById('main');
const original = document.getElementByid('operation1');
const clone = original.cloneNode(true);

main.replaceWith(clone);

This would probably present an issue the next time you go to swap the element, but you could adapt this solution to fit your needs.

这可能会在您下次交换元素时出现问题,但您可以调整此解决方案以满足您的需求。



Original Post:

原帖:

The best way to do this would be to notuse innerHTML, due to possible unforseen side effects. The best way to do this would be to:

最好的方法是不要使用innerHTML,因为可能有不可预见的副作用。最好的方法是:

  • First clone the desired div
  • Second empty the main div
  • Third append the clone into the main div
  • 首先克隆所需的div
  • 第二个清空主div
  • 第三次将克隆附加到主 div 中

This would look very much like the following:

这将非常类似于以下内容:

function swapContent (id) {
    const main = document.getElementById('main');
    const div = document.getElementById(id);
    const clone = div.cloneNode(true);

    while (main.firstChild) main.firstChild.remove();

    main.appendChild(clone);
}

Do not allow yourself to fall into the many pitfalls of using innerHTML; cloning a node has a much better chance of doing exactly what you're expecting it to do.

不要让自己陷入使用的许多陷阱innerHTML;克隆一个节点更有可能完全按照您的期望去做。

Some of the problems with innerHTMLare that it only copies the HTML, and not the DOM, meaning that you do not copy over anything on that DOM node, like event listeners, properties (like value), etc. Cloning a node (and its children) clone that DOM node, which clones its properties respectively.

一些问题innerHTML是它只复制 HTML,而不是 DOM,这意味着您不会复制该 DOM 节点上的任何内容,如事件侦听器、属性(如值)等。克隆节点(及其子节点) ) 克隆那个 DOM 节点,它分别克隆其属性。

It is also considered poor practice (by most) to use inline event handlers on your HTML; separation of concerns!

在 HTML 上使用内联事件处理程序也被认为是糟糕的做法(大多数);关注点分离!

回答by ilosi

i used this form for replace my divs.

我用这个表格来替换我的 div。

<div id="newDiv" class="here" style="display: none" > content</div>
<div id="oldDiv" class="here" style="display: block"> content</div>
<button type="button" onclick="newDivHere()">replace</button>

and JS:

和JS:

function newDivHere() {
document.getElementById("oldDiv").style.display="none";
document.getElementById("newDiv").style.display="block";
}

回答by JTrixx16

Edit your javascript like this:

像这样编辑你的javascript:

function show(param_div_id){
    document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).textContent;
}


And also, put your parameters inside single-quotes like this:


而且,将您的参数放在单引号中,如下所示:

<button onclick="show('operation1')">

回答by Regis Portalez

just assign the HTML content to a string (manually written or fetched from another html element (template)):

只需将 HTML 内容分配给一个字符串(手动编写或从另一个 html 元素(模板)获取):

window.onload = function() {
  document.getElementById("to_be_replaced").innerHTML = "<span> My Production Text </span>";
}
div > span {
  font-weigth: bold;
  color: red;
  }
<div id="to_be_replaced">
  Lorem ipsum...
</div>

回答by user3617558

i think ndugger is right and you should use something like delete/colon or in jquery .remove() and append() instead of innerhtml.

我认为 ndugger 是对的,你应该使用像 delete/colon 或 jquery .remove() 和 append() 之类的东西,而不是innerhtml。

according to this question in stackoverflow and other sites always better use append() instead of html() or innerHTML.

根据 stackoverflow 和其他站点中的这个问题,总是更好地使用 append() 而不是 html() 或 innerHTML。

"innerHTML += ..." vs "appendChild(txtNode)"

“innerHTML += ...” vs “appendChild(txtNode)”

your code can be like this.

你的代码可以是这样的。

        function swapContent(id) {
            const main = document.getElementById('main_place');
            const div = document.getElementById(id);
            const clone = div.cloneNode(true);

            while (main.firstChild) main.firstChild.remove();

            main.appendChild(clone);
        }
    <div id="main_place">
        main
    </div>

    <button onclick="swapContent('operation1')">Replace to operation 1</button>
    <button onclick="swapContent('operation2')">Replace to operation 2</button>
    <button onclick="swapContent('operation3')">Replace to operation 3</button>

    <div id="complete" style="display:none;">
        <div id="operation1">
            Some textboxes and text
        </div>

        <div id="operation2">
            Again some textboxes and text
        </div>

        <div id="operation3">
            And again some textboxes and text
        </div>
    </div>

also you can use

你也可以使用

document.getElementById("idOfDIv").addEventListener("click", function () {
    yourfunction();
    secondfunction();
})

or this

或这个

document.getElementById("idOfDIv").onclick = yourfunction();

instead of inside HTML onclick Event Attribute

而不是在 HTML onclick 事件属性中