[英]javascript jquery add stylesheet if class is present
Can anyone tell me why the following doesn't work in my 'head' 任何人都可以告诉我为什么以下不适用于我的'头'
<script type="text/javascript">
if ($('.company-color').length){
document.write("<link rel='stylesheet' href='company-color.css' type='text/css'>");
}
</script>
I have a class that is only present on some pages and I want to insert the above stylesheet to the page if the class '.company-color' is present. 我有一个只出现在某些页面上的类,如果存在类'.company-color',我想将上面的样式表插入页面。
use 采用
jQuery(function($){
if ($('.company-color').length){
$('body').append("<link rel='stylesheet' href='company-color.css' type='text/css'>"); // or to head
}
})
Try this code : 试试这段代码:
$(function(){
if ($('.company-color').length > 0){
$('head').append('<link rel="stylesheet" href="company-color.css" type="text/css">');
}
})
You have to use the append method to add your css to the head element. 您必须使用append方法将css添加到head元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.