【问题标题】:How to show another HTML file's contents on the same page when a link is clicked?单击链接时如何在同一页面上显示另一个 HTML 文件的内容?
【发布时间】:2013-02-03 06:49:32
【问题描述】:

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

【问题讨论】:

  • 例子? another html 是什么?问题越好,答案就越好。尽量详细。还请提及您尝试过的内容,以便我们更好地了解您的目标。
  • 接下来我要尝试什么...我的左侧有链接...我需要在链接所在的同一页面中显示此链接中的文本...
  • 您是要加载另一个页面,还是要在屏幕上实际打印出 html 代码?

标签: javascript html anchor href


【解决方案1】:

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

  • iFrame
    要创建 iframe,请将其放入源代码中:<iframe src="the/URL/of/a/page.html"></iframe>。这将在 iframe 中的the/URL/of/a/page.html 处显示文件。 iframe 可以使用 CSS 设置样式(仅供参考)。然后给你所有的<a>s 一个类,我用link 作为我的示例 JavaScript,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)。请注意,AJAX 通常仅适用于来自同一域的文件,这与 iframe 解决方案相反(尽管我相信我在 SO 上看到了一些解决方法/hacks)。例子:

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

注意:我没有测试任何这些。

【讨论】:

  • OP 没有提到“其他 HTML”将来自另一个域,所以我自动假设它只是一个导航栏。感谢您指出这一点,我会将其包含在我的答案中@cIph3r
  • 更好,但是对于 SO 的 hack,您可能会参考 JSONP、代理文件或跨域策略文件
  • 我认为 OP 还没有做到这一点,所以我没有扩展它,但是:是的,你是对的。 @cIph3r
猜你喜欢
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2013-12-17
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多