【问题标题】:Removing <link> element with jQuery?用 jQuery 删除 <link> 元素?
【发布时间】:2010-11-01 04:00:26
【问题描述】:

我不想使用 style.css 中的样式,所以我决定从 DOM 中删除 style.css。这在 Firefox 和 IE8 中运行良好,但在 IE6 中不行:

$("LINK[href='http://www.example.com/style.css']").remove();

任何其他解决方案,使用 jQuery?


这里是示例:
HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("link[href*='style.css']").remove();         
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="content">...</div>
</body>
</html>

这里是 CSS (style.css):

#content {
    background-color:#333;
}

仅在 IE 中 #content 仍然是黑暗的。 :(
也许是 jQuery 的错误?

【问题讨论】:

    标签: javascript jquery css dom


    【解决方案1】:

    这不是 jQuery 的错误,它是 IE 渲染引擎的错误(或者可能是一个特性)。

    此问题似乎是由于 Internet Explorer 在从 DOM 中删除 LINK 元素后未正确重新呈现页面所致。

    在这种特殊情况下,DOM 中不再存在 LINK 标记,但 IE 仍显示已加载到内存中的 CSS。

    解决方法/解决方案是使用 .disabled 属性禁用样式表,如下所示:

    // following code will disable the first stylesheet
    // the actual DOM-reference to the element will not be removed; 
    // this is particularly useful since this allows you to enable it
    // again at a later stage if you'd want to.
    document.styleSheets[0].disabled = true;
    

    编辑回复您的评论:

    或者,如果您想通过 href 删除它,请使用以下代码:

    var styleSheets = document.styleSheets;
    var href = 'http://yoursite.com/foo/bar/baz.css';
    for (var i = 0; i < styleSheets.length; i++) {
        if (styleSheets[i].href == href) {
            styleSheets[i].disabled = true;
            break;
        }
    }
    

    【讨论】:

    • 感谢您的回答,但这不是我想要的。我不知道元素索引,因为它是可变的。关于这个元素,我唯一知道的是 href 值。
    • 我刚刚添加了一个额外的例子,如果你只有 href 应该可以解决这个问题
    • 它在FF中不起作用,但我添加了 $("link[href*='style.css']").remove();在 for 声明之后,现在一切正常。谢谢:)
    • 感谢您跟进该 sasa,在 Chrome 中的工作就像一个魅力。还没有跨浏览器测试!
    【解决方案2】:

    也许这是 IE6 对href 属性中的 URL 所做的一些奇怪的事情?尝试类似:

    $("LINK[href*='style.css']").remove();
    

    (即检查href值是否包含“style.css”)

    不过,这只是一个猜测。如果这不起作用,我建议仔细检查有关属性选择器和 remove 方法的 JQuery 文档。

    还要记住,它实际上是一个错误也不是不可能的。 (IE6 通常会导致许多涉及 JavaScript 和 DOM 操作等问题。)

    【讨论】:

    • 看来肯定不行。我已经更新了我的帖子。也许是 jQuery 中的错误或其他什么......
    【解决方案3】:

    话题比较老了,但是你只能给你的link元素添加ID,然后逐个元素删除:

    $("#id").remove();
    

    【讨论】:

    • 快进 3 年,这对我来说是解决完全相同问题的答案。非常感谢!
    【解决方案4】:

    也许在标签名称上使用小写?

    【讨论】:

    • 您好,您解决了这个问题吗?我想我在同一条船上:))。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2015-07-08
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多