【问题标题】:include html page-code into another [html]-file将 html 页面代码包含到另一个 [html] 文件中
【发布时间】:2014-09-03 01:32:29
【问题描述】:

好的,这就是我想要做的:

将外部 html 文件的页眉和页脚包含到另一个 html 文件中。

我知道,这里有很多可用的 sn-ps。但是……

...问题:我无法修改那些外部 html,它们包含一个完整的 <head> 以及元、链接和所有内容。

这是我找到的代码-sn-ps(来自@amir-saniyan - github):

(function ($) {
  $.include = function (url) {
    $.ajax({
      url: url,
      async: false,
      success: function (result) {
        document.write(result);
      }
    });
  };
}(jQuery));
$.include("_header.html");
$.include("_footer.html");

$crop_start = (result.indexOf('<body>') !== -1) ? result.indexOf('<body>') + 7 : 0;
$crop_end = (result.indexOf('</body>') !== -1) ? result.indexOf('</body>') : result.length;
result = result.substring($crop_start, $crop_end);

如何合并两个html-code结构以获得预期的结果:

  • 将该外部html 导入另一个,但没有头部(只有 html-&lt;body&gt;&lt;/body&gt; 标签之间的代码)

【问题讨论】:

    标签: jquery html ajax include


    【解决方案1】:

    在'_header.html'和'_footer.html'的'body'标签下直接添加一个'div'来保存所有的HTML内容(因为jQuery在解析时会去掉'head'标签和'body'标签HTML 字符串):

    <body>
        <div id="wrapper">
        ...
        </div>
    </body>
    

    然后,替换您手动提取的 html 内容

    $crop_start = (result.indexOf('<body>') !== -1) ? result.indexOf('<body>') + 7 : 0;
    $crop_end = (result.indexOf('</body>') !== -1) ? result.indexOf('</body>'):result.length;
    result = result.substring($crop_start, $crop_end);
    

    通过

    result = $(result).filter("#wrapper").html();
    

    通过更改将上述解决方案应用于您的“包含”函数:

    document.write(result);
    

    result = $(result).filter("#wrapper").html();
    $("body").append(result);  
    

    注意: 请记住,$.ajax 调用中的 'async' 必须为 'false' 才能将页眉和页脚加载到正确的位置。

    【讨论】:

    • 谢谢,这是个好主意。现在,我如何将它与第一个 sn-p 一起使用?
    • 添加了与第一个 sn-p 一起使用的描述
    【解决方案2】:

    您可能需要更精确地提出您的要求,因为您没有定义“页眉”和“页脚”。在您提供的 jQuery 代码 sn-p 中,该 sn-p 应该是一个更大的 HTML 文件的一部分,该文件包括诸如“

    ”标签(“header”的一种定义)之类的东西。这也是一种破坏性的 sn-p,因为 document.write() 函数往往会导致已经加载的 HTML 页面上的几乎所有内容都被替换(包括 JavaScript!)。

    考虑用类似这样的方式替换对 document.write() 函数的调用(尚未测试是否有错别字):

     var txt;   //declare this variable somewhere,
                // not necessarily in the code-snippet function
    
     txt = document.createElement("p"); //paragraph tag
     txt.innerHTML = result;
     document.body.appendChild(txt);
    

    此代码假定您的 HTML 页面已经有一个

    标记对,它们之间可能没有任何内容。

    【讨论】:

    • 您好,感谢您的回答。我知道我在我的第一个 sn-p 中没有定义任何东西。它只是将页面导入我的页面,这就是我想要的......除了正文标签之间的代码之外没有任何其他内容。这就是第二个 sn-p 应该做的......但我不知道如何使用它。
    • 在我看来,第二个 sn-p 只是修剪一长串 HTML 文本,删除之前/包括开始正文标记的所有内容,以及之后/包括结束正文标记的所有内容。如果该字符串是您要插入到加载/修剪它的页面中的内容,那么我编写的关于 createElement 和 appendChild 的代码应该可以解决问题 - 只需在另一个函数中执行,与您的第一个 sn-p 中的不同包含 document.write().
    • 谢谢vernonner3voltazim!这第二个 sn-ps 实在是太复杂了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2014-07-03
    • 2019-01-04
    • 1970-01-01
    • 2021-06-28
    • 2013-06-13
    • 2012-02-17
    相关资源
    最近更新 更多