首页 > 解决方案 > 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 相同的小提琴:

https://jsfiddle.net/14fy0u3o/

标签: javascriptjqueryhtmlcss

解决方案


你的两个小提琴仍然有 jQuery。它只是一个不包含 cookie 库的产品。没有 cookie 库的那个是可以工作的,因为您的点击处理程序永远不会设置。

这是因为您的代码在第一行出错了ShowPrices()

if($.cookie('VATMODE') == "INC"){

因为$.cookie没有定义 cookie 库,所以会引发错误。如果您打开控制台(F12 -> 控制台选项卡,在大多数浏览器上),您会看到一些错误,例如Uncaught TypeError: $.cookie is not a functionThis 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语句。


推荐阅读