【问题标题】:Replace all references to external files (images, CSS and JavaScript) with flat directory references?用平面目录引用替换所有对外部文件(图像、CSS 和 JavaScript)的引用?
【发布时间】:2010-12-08 21:04:59
【问题描述】:

我试图弄清楚是否有办法(使用 JavaScript 或 jQuery)遍历整个 HTML 文件,替换对外部文件的所有引用,并将对其他目录中文件的所有引用替换为相同的命名文件,但没有目录信息。

例如,在 HTML 文本中:

  • scripts/script.js 被替换为 script.js
  • images/big.jpg 被替换为 big.jpg
  • css/style.css 被替换为 style.css

等等

我猜 CSS 文件中的引用也需要更改。

【问题讨论】:

  • 因为我想在本地保存 html,而不是能够在没有连接的情况下正确查看页面。创建相同的目录结构(特别是如果外部文件位于不同的域中)是站不住脚的,所以我需要“扁平化”目录结构。
  • 我知道至少在 Firefox 中,您可以执行 File -> Save Page As 然后选择“另存为类型:网页,完成”,Firefox 将下载所有 js/css/img 文件本地并为您更新 HTML 文档。否则,JavaScript 不是执行此操作的正确方法。

标签: javascript jquery html css dom


【解决方案1】:

下面的代码很乱,会很整洁,但希望你解决你需要的。

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript">

$(function(){

    $("*", $("#container")).each(function()
    {
        try
        {
            //src
            if ($(this).attr("src"))
                if ($(this).attr("src").lastIndexOf("/")!=-1)
                    $(this).attr("src", $(this).attr("src").substr($(this).attr("src").lastIndexOf("/")+1) );

            //href
            if ($(this).attr("href"))
                if ($(this).attr("rel"))
                    if ($(this).attr("rel")=="stylesheet")
                        if ($(this).attr("href").lastIndexOf("/")!=-1)
                            $(this).attr("href", $(this).attr("href").substr($(this).attr("href").lastIndexOf("/")+1) );
        }
        catch(ex)
        {
            $("#lstError").append("<div>"+ex.description+"</div>");
        }
    });

});

</script>
</head>
<body>

    <div id="lstError"></div>

    <div id="container">
        <!-- your html -->
        <link rel="stylesheet" href="pepe/all.css">
        <img src="lele/bl.png" />
        <img src="lele/b.png" />
    </div>

</body>
</html>

【讨论】:

  • 这只是做你需要的一种方法@cannyboy。保险不是一个好的做法,因为它会产生许多 404 错误。
【解决方案2】:

您的浏览器的页面另存为...怎么样?

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多