javascript - jQuery cookie 破坏了我的 CSS 切换输入
问题描述
我正在使用 jQuery Cookies 和 jQuery hide and show 结合复选框切换来控制何时显示价格。
<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()
if($.cookie('VATMODE') == "INC"){
因为$.cookie
没有定义 cookie 库,所以会引发错误。如果您打开控制台(F12 -> 控制台选项卡,在大多数浏览器上),您会看到一些错误,例如Uncaught TypeError: $.cookie is not a function
This error then has the effect of the rest of your code in the function not running
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
语句。
推荐阅读
- javascript - 来自 2 个 MySQL 查询的数组将用于 2 个使用 javascript 的选择
- excel - 更新外部链接和文件位置 Excel
- scikit-learn - 将 scikit-learn 0.17 版代码翻译成 0.20 版
- performance - 实时收集 Linux 上运行的 .Net Core 2.1 应用程序的 GC 指标
- php - 如何将 xdebug “导入”到现有的 php docker 容器中
- javascript - 使用 css/javascript 更改图例背景颜色
- ios - 在 Objective-C 中放置主线程阻塞操作的最佳生命周期方法
- android - 为什么 androidx espresso .check() 会导致 androidx.test.espresso.IdlingResourceTimeoutException
- xml - 使用 XSLT 文件将 XML 转换为 XML
- excel - Excel UDF 按名称指定表格行和列