繁体   English   中英

如果有类,则javascript jquery添加样式表

[英]javascript jquery add stylesheet if class is present

任何人都可以告诉我为什么以下不适用于我的'头'

<script type="text/javascript">

if ($('.company-color').length){
    document.write("<link rel='stylesheet' href='company-color.css' type='text/css'>");
}

</script>

我有一个只出现在某些页面上的类,如果存在类'.company-color',我想将上面的样式表插入页面。

采用

jQuery(function($){
    if ($('.company-color').length){
        $('body').append("<link rel='stylesheet' href='company-color.css' type='text/css'>"); // or to head
    }
})

试试这段代码:

$(function(){
    if ($('.company-color').length > 0){
        $('head').append('<link rel="stylesheet" href="company-color.css" type="text/css">');
    }
})

您必须使用append方法将css添加到head元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM