我想创建加载复选框并隐藏CSS样式表文件。
我制作复选框,而不是将样式表附加到页面。
现在,当我选中未发生在页面上的复选框时
我的JS
<script>// RTL
$('#show_rtl').change(function(){
if($(this).is(":checked")){
$('head').append('<link media="all" type="text/css" href="../css/rtl.css" id="thr_rtl_css_custom" rel="stylesheet">')
} else {
$('#thr_rtl_css_custom').remove();
}
});
</script>
HTML复选框输入:
<label>
<input class="sw-title" type="checkbox" id="show_rtl"> Right to left (RTL)
</label>
谢谢!
答案 0 :(得分:0)
您正在尝试在文档完全加载之前附加onchange处理程序。因此,您尝试将其附加到的DOM元素/复选框此时不存在。
像这样重写你的脚本:
$(document).ready(function(){
$('#show_rtl').change(function(){
if($(this).is(":checked")){
$('head').append('<link media="all" type="text/css" href="../css/rtl.css" id="thr_rtl_css_custom" rel="stylesheet">')
}else{
$('#thr_rtl_css_custom').remove();
}
});
});
$(document).ready()
函数确保在页面加载完成之前不会执行它传递的函数。它也可以像这样简写:$(function() { <your code here> });
答案 1 :(得分:0)
我建议您不要这样做,因为每次选中复选框时都会发出请求。
您可以做的是根据将在父元素中切换的类添加规则。通过这种方式,您可以添加&#34;从右到左&#34;默认样式表中的css规则。
$('#checkMe').click(function(){
$('#mainElement').toggleClass('show_rtl');
});
&#13;
.show_rtl p{
direction: rtl;
}
.blueOrRed{
background: blue;
width:100px;
height:100px;
float:left;
}
.show_rtl .blueOrRed{
background: red;
float: right;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mainElement">
<input type="checkbox" id="checkMe" value="toggle Class">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<div class="blueOrRed"></div>
</div>
&#13;