繁体   English   中英

单击链接时如何在同一页面上显示另一个HTML文件的内容?

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

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

简单的解决方案: iframe ,更好但更难的解决方案: AJAX

  • iFrame
    要创建iframe,请将其放入您的源代码中: <iframe src="the/URL/of/a/page.html"></iframe> 这将在iframe中的the/URL/of/a/page.html中显示文件。 可以使用CSS(仅供参考)设置iframe的样式。 然后给您所有的<a> sa类,我为示例JavaScript设置了link ,并为iframe设置了ID(我采用了iframe )。 (如果没有JS AFAIK,则无法做到这一点,否则您将不得不使用已废弃的<frameset> 。)示例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
    这有点困难,使用jQuery之类的库极大地简化了此任务。 在我的示例中,我使用jQuery,否则它将花费更多的代码行。
    您需要一个div来显示加载的页面,在页面上放一个并为其指定ID(在示例中使用了resultbox )。 请注意,与iframe解决方案相反,AJAX通常仅适用于同一域中的文件(尽管我相信我在SO上看到了一些解决方法/漏洞)。 这个例子:

     $(".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' }); 

注意:我没有测试任何一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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