简体   繁体   中英

How to change the content of a div on one html page with the contents of a div from another page using javascript?

I want to use a link in a TOC (eg, click me) to replace the current contents of a div on one page with the contents of a div on another page. I'd like to do this just using JavaScript.

Here is the code from the two pages:

Original Page (to receive new content)

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>

<script type= "text/javascript">
    function loadContent(targetPage){
        document.getElementById("content").innerHTML = "New text!"; //How do I change this to get the contents of a div in another HTML file?
    }

</script>
</head>

<body>
<div id="link">
    <a href="#"  onClick="loadContent("newContent.html")">Click Me.</a>
    </div>
    <p></p>
<div id="content">
    <p>This is the original content.</p>
</div>


</script>
</body>
</html>

Source Page

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Source</title>
</head>

<body>

<div id="newContent">
    <p>New Content:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in. Est velit egestas dui id ornare arcu. Ultricies leo integer malesuada nunc vel. Risus sed vulputate odio ut. Senectus et netus et malesuada fames ac turpis egestas.</p>
</div>

</body>
</html>

You can use iframe to place one html page inside another. I changed the inner content of the div to a iframe with the html page as the src. I also added a style to make the iframe the size of the page.

<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
.p2iframe{
width:100%;
height:100%;
float:left;
border:0px;
overflow:hidden;    
}
</style>
<script type= "text/javascript">
function loadContent(){
document.getElementById("content").innerHTML = "<iframe class=\"p2iframe\" src=\"page2.html\" name=\"p2iframe\"></iframe>"; 
}
</script>
</head>
<body>
<div id="link"><a href="#"  onClick="loadContent();">Click Me.</a></div>
<div id="content"><p>This is the original content.</p></div>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM