【问题标题】:How to replace div with another div in javascript?如何在javascript中用另一个div替换div?
【发布时间】:2021-11-29 06:00:55
【问题描述】:

如何在 javascript 中用另一个 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 = Here should be div from param;
        }
</script>

没有jquery也能做到吗?

【问题讨论】:

标签: javascript html


【解决方案1】:

将字符串传递给您的方法并获取另一个 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>

【讨论】:

  • 我建议innerHTML 和内联事件处理程序的一些替代方案。
  • @Cerbrus 我相信 DiPix 只是想完成他的代码。就是这样。下一步改进
  • 是的,但 SO 答案应尽可能解决 OP 代码的所有问题。
  • 这也是事实,SO 是一个社区......我不能保证解决你所有的问题,但我可以保证你不必独自面对它们;)跨度>
  • @Lee.Winter 是当天的英雄 :-)
【解决方案2】:

2019 年更新:

child.replaceWith(newElement);

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

在这个问题的具体情况下,我建议使用 replaceWith 和 OP 希望交换的节点的克隆。这可能看起来像:

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

main.replaceWith(clone);

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


原帖:

最好的方法是使用innerHTML,因为possible unforseen side effects。最好的方法是:

  • 首先克隆所需的div
  • 第二次清空主 div
  • 第三次将克隆附加到主 div 中

这看起来很像以下内容:

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);
}

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

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

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

【讨论】:

  • 您能否更具体地了解这些“可能的不可预见的副作用”,说在抨击另一个完全可以接受的答案的同时,如果您更具建设性会有所帮助
  • campaign:5 Uncaught TypeError: Cannot read property 'firstChild' of null,为什么?
  • 使用 innerHTML 不仅会清除您设置它的节点上的事件侦听器,而且它也不会继承该 HTML 的子节点的任何事件侦听器(除非您使用的是内联 HTML事件,这也是不好的做法)。拜托,让我们写好代码,好吗?
  • @ndugger - 良好的链接,但了解何时以及如何使用事物更重要,它并不是因为您链接的那篇文章而在全球范围内“坏”。我知道如果我用锤子敲我的脚趾会很痛,但这并不会使锤子坏。无论哪种方式,感谢您的编辑,这对未来的读者更有帮助。
  • @DiPix 具体是什么部分?这是非常简单的代码;我建议您在尝试编写它之前查看 CodeCademy.com 以了解该语言的基础知识。
【解决方案3】:

我用这个表格来替换我的 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>

和 JS:

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

【讨论】:

  • 虽然这是隐藏一个 div 并显示另一个 div 的好解决方案,但在这里它可能不是一个“正确”的解决方案,因为 OP 专门询问了如何“交换”或“替换”一个元素或其内容。不过,我仍然会为你的帖子 +1,因为你是新人。
【解决方案4】:

这样试试

document.querySelector('#maincontent').outerHTML = jsonResponse.main;

【讨论】:

    【解决方案5】:

    只需将 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>

    【讨论】:

      【解决方案6】:

      像这样编辑你的javascript:

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


      此外,将参数放在单引号中,如下所示:

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

      【讨论】:

        【解决方案7】:

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

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

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

        您的代码可以是这样的。

                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>

        你也可以使用

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

        或者这个

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

        而不是HTML里面的onclick事件属性

        【讨论】:

          猜你喜欢
          • 2011-07-01
          • 1970-01-01
          • 2011-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-03
          • 2015-11-24
          相关资源
          最近更新 更多