[英]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
,更好但更难的解决方案: AJAX
。
iFrame iFrame
To create an iframe put this in your source code: <iframe src="the/URL/of/a/page.html"></iframe>
. 要创建iframe,请将其放入您的源代码中: <iframe src="the/URL/of/a/page.html"></iframe>
。 That would display the file at the/URL/of/a/page.html
in the iframe. 这将在iframe中的the/URL/of/a/page.html
中显示文件。 An iframe can be styled with CSS (just FYI). 可以使用CSS(仅供参考)设置iframe的样式。 Then give all your <a>
sa class, I took link
for my example JavaScript, and the iframe an ID (I took iframe
). 然后给您所有的<a>
sa类,我为示例JavaScript设置了link
,并为iframe设置了ID(我采用了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: (如果没有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 AJAX
That's a little bit harder, and using a library like jQuery simplifies this task enormously. 这有点困难,使用jQuery之类的库极大地简化了此任务。 In my example I use jQuery, otherwise it would have taken much more lines of code. 在我的示例中,我使用jQuery,否则它将花费更多的代码行。
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). 您需要一个div
来显示加载的页面,在页面上放一个并为其指定ID(在示例中使用了resultbox
)。 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). 请注意,与iframe
解决方案相反,AJAX通常仅适用于同一域中的文件(尽管我相信我在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. 注意:我没有测试任何一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.