首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从外部html文件复制div并将其保存到其他html文件中

如何从外部html文件复制div并将其保存到其他html文件中
EN

Stack Overflow用户
提问于 2021-08-20 08:33:45
回答 2查看 66关注 0票数 0

我想从外部文件复制一个HTML文件,并通过单击按钮并使用JavaScript将其保存到其他div文件中:

代码语言:javascript
运行
复制
<html lang="en">
  <head>
    <title>Document 1</title>
  </head>
  <body>
    <div class="container1">
      <p>text 1</p>
    </div>

  </body>
</html>
    
<html lang="en">
  <head>
    <title>Document 2</title>
  </head>
  <body>
    <div class="container2">
      <p>text 2</p>
    </div>
    <button>Click here</button>
  </body>
</html>
EN

回答 2

Stack Overflow用户

发布于 2021-08-20 09:18:56

使用普通的JavaScript:

代码语言:javascript
运行
复制
<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Page A</title>
</head>
<body>
  <div id="target"></div>
  <button onclick="loadElement('b.html', 'div#y', 'div#target')">Copy div#y from b.html</button>
  <script>
    async function loadElement(sourceFileName, sourceSelector, targetSelector) {
      // Load the whole <body> of the source HTML file
      const response = await fetch(sourceFileName);
      const text = await response.text();
      const i1 = text.indexOf("<body>");
      const i2 = text.indexOf("</body>");
      const bodyHTML = text.substring(i1 + "<body>".length, i2);

      // Add it to the target element
      const targetElement = document.body.querySelector(targetSelector);
      targetElement.innerHTML = bodyHTML;

      // Keep only the source element
      const sourceElement = targetElement.querySelector(sourceSelector);
      targetElement.innerHTML = "";
      targetElement.append(sourceElement);
    }
  </script>
</body>
</html>

要从中加载div的文件:

代码语言:javascript
运行
复制
<!-- b.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page B</title>
</head>
<body>
    <div>
        <div>
            <div id="x">Hello from b.html div#x!</div>
            <div id="y">Hello from b.html div#y!</div>
        </div>
        <div id="z">Hello from b.html div#z!</div>
    </div>
</body>
</html>

我通过从这些文件所在的文件夹中启动Python web server on Windows (py -m http.server),并在Chrome中打开http://localhost:8000/a.html来测试这一点。单击该按钮将从b.html加载选定的div。

票数 1
EN

Stack Overflow用户

发布于 2021-08-20 09:12:58

使用jQuery可以解决您的问题。如果您想将sampleA.html中的div (id = "DivA")内容放到当前的html div (id= "DivB")中。假设这两个html文件位于相同的路径下。

代码语言:javascript
运行
复制
$( "#DivB" ).load( "sampleA.html #DivA" );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68859239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档