[英]jQuery cookie breaking my CSS toggle input
我正在使用jQuery Cookies和jQuery隐藏和显示以及复选框切换来控制何时显示价格。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round">
<span class="on">Incl</span>
<span class="off">Excl</span>
</div>
</label>
<span class="price-excluding-tax">
<span class="label">Excl. Tax:</span>
<span class="price" id="price-excluding-tax-3">€9.99</span>
</span>
<span class="price-including-tax">
<span class="label">Incl. Tax:</span>
<span class="price" id="price-including-tax-3">€9.99</span>
</span>
<script type="text/javascript">
(function($){
$(function(){
ShowPrices();
$('input#togBtn').click(function(){
if($.cookie('VATMODE') == "INC"){
$.cookie('VATMODE', 'EX');
} else {
$.cookie('VATMODE', 'INC')
}
ShowPrices();
return false
});
});
function ShowPrices(){
if($.cookie('VATMODE') == "INC"){
$('.price-including-tax').show();
$('.price-excluding-tax').hide();
} else {
$('.price-including-tax').hide();
$('.price-excluding-tax').show();
}
}
})(jQuery);
</script>
jQuery破坏了我的CSS切换功能,并且在我的生命中我无法弄清楚原因,这工作正常。
这是一个摆弄问题的小提琴(请注意切换开关不会切换):
https://jsfiddle.net/ra5t0hfo/7/
并删除了与jQuery相同的小提琴,在我的切换正常的情况下:
你们两个小提琴仍然使用jQuery。 这只是其中一个没有cookie库的地方。 没有cookie库的库是可以使用的库,因为您的点击处理程序从未设置。
这是因为您的代码在ShowPrices()
的第一行ShowPrices()
if($.cookie('VATMODE') == "INC"){
由于不存在Cookie库,因此未定义$.cookie
因此引发错误。 如果打开控制台(在大多数浏览器中Uncaught TypeError: $.cookie is not a function
>控制台选项卡),您会看到类似Uncaught TypeError: $.cookie is not a function
错误Uncaught TypeError: $.cookie is not a function
此错误会影响函数中其余代码的影响
ShowPrices(); //error happens in ShowPrices, execution stops here does not continue
$('input#togBtn').click(function(){
//...
});
使用cookie库的那个库不起作用的原因是,永远不会引发该错误,并且您的点击处理程序已设置。 并且您在该处理程序中return false
,这防止了复选框更改状态的默认操作
jQuery("#thecheck").click(function(){ return false });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="thecheck">
如果希望复选框可切换,请取出return false
语句。
为什么用$('input#togBtn')
返回false
? 删除退货作品。
检查小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.