简体   繁体   中英

How to show another HTML file's contents on the same page when a link is clicked?

当我在页面左侧有几个链接时,如何在单击链接时在同一页面上显示另一个HTML文件的内容?

Simple solution: iframe s, nicer but slightly harder solution: AJAX .

  • iFrame
    To create an iframe put this in your source code: <iframe src="the/URL/of/a/page.html"></iframe> . That would display the file at the/URL/of/a/page.html in the iframe. An iframe can be styled with CSS (just FYI). Then give all your <a> sa class, I took link for my example JavaScript, and the iframe an ID (I took iframe ). (There is no way to do it without JS AFAIK, or you would have to use a <frameset> , which is deprecated.) The example JS:

     var links = document.getElementsByClassName("link"); // Get all the elements with the class link for (var i; i < links.length; i++) { // Loop over all the links links[i].onclick = function(e) { // Tell them what to do when they're clicked e.preventDefault(); // Prevent the browser from navigating to the address of the links href document.getElementById("iframe").src = links[i].href; // Set the iframe's src to the href of the a. } } 
  • AJAX
    That's a little bit harder, and using a library like jQuery simplifies this task enormously. In my example I use jQuery, otherwise it would have taken much more lines of code.
    You need a div to display the loaded page, put one on your page and give it an ID (I used resultbox in my example). Note that AJAX normally only works with files from the same domain, contrary to the iframe solution (although I believe I saw some workarounds/hacks on SO). The example:

     $(".link").click(function(e) { // If an element with the class 'link' get's clicked... e.preventDefault(); $("#resultbox").load("the/URL/of/a/page.html"); // ... load the contents of the file at the/URL/of/a/page.html into the element with the ID 'resultbox' }); 

Note: I didn't test any of this.

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