我想从外部文件复制一个HTML文件,并通过单击按钮并使用JavaScript将其保存到其他div
文件中:
<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>
发布于 2021-08-20 09:18:56
使用普通的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的文件:
<!-- 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。
发布于 2021-08-20 09:12:58
使用jQuery可以解决您的问题。如果您想将sampleA.html中的div (id = "DivA")内容放到当前的html div (id= "DivB")中。假设这两个html文件位于相同的路径下。
$( "#DivB" ).load( "sampleA.html #DivA" );
https://stackoverflow.com/questions/68859239
复制相似问题