用jQuery删除<link>元素?

sas*_*asa 12 javascript css jquery dom

我不想使用style.css中的样式,所以我决定从DOM中删除style.css.这在Firefox和IE8中工作得很好,但在IE6中却没有:

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

使用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>
Run Code Online (Sandbox Code Playgroud)

这是CSS(style.css):

#content {
    background-color:#333;
}
Run Code Online (Sandbox Code Playgroud)

仅在IE #content中仍然是黑暗的.:(
也许是jQuery bug?

Aro*_*eel 20

这不是jQuery中的错误,它是IE渲染引擎的错误(或可能是一个功能).

看来这个问题是由于从DOM中删除LINK元素后Internet Explorer没有正确地重新呈现页面这一事实.

在这种特殊情况下,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;
Run Code Online (Sandbox Code Playgroud)

编辑回复您的评论:

或者,如果要通过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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Nol*_*rin 9

也许IE6对href属性中的URL做了什么奇怪的事情?尝试类似的东西:

$("LINK[href*='style.css']").remove();
Run Code Online (Sandbox Code Playgroud)

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

然而,这只是猜测.如果这不起作用,我建议关于属性选择器和remove方法的主题密切检查JQuery文档.

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


小智 5

主题已经很老了,但是您只能将ID添加到链接元素中,并按元素将其删除:

$("#id").remove();
Run Code Online (Sandbox Code Playgroud)