用复选框替换了切换按钮但不起作用

时间:2017-05-10 12:39:20

标签: javascript jquery html checkbox

我用一个复选框替换了jQuery切换代码上的按钮但无法使其工作。

这是我试图用复选框

替换按钮的HTML文件

的index.html

<p> hi </p>
<!--<button>Press me</button>-->
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>

的javascript

$(function() {

    if (Cookies) {
        $("p").toggle(!( !! Cookies("toggle-state")) || Cookies("toggle-state") === 'true');
    }

    // $('button').on('click', function()
    $('#myonoffswitch.onoffswitch').is(":checked"), function() 
     {
        $("p").toggle();
        Cookies.set("toggle-state", $("p").is(':visible'), {
            expires: 1,
            path: '/'
        });
    });

});

Fiddle

这里有什么问题?

2 个答案:

答案 0 :(得分:3)

&#13;
&#13;
$(function() {
 

      $('#myonoffswitch').click(function(){
              /*Use toggle if you need only hide and show */
              //$("p").toggle(); 
              
              /*If you want to know the current status of checkbox       go with below code*/
          if($(this).is(':checked')){
                  $("p").show();
          }else{
                  $("p").hide();
          }
      })
  

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> hi </p>
<!--<button>Press me</button>-->
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>
&#13;
&#13;
&#13;

  $('#myonoffswitch.onoffswitch').is(":checked"), function() 
     {
        $("p").toggle();
        Cookies.set("toggle-state", $("p").is(':visible'), {
            expires: 1,
            path: '/'
        });
    }); 

将此代码更改为

       $('#myonoffswitch').click(function(){
          /*Use toggle if you need only hide and show */
          //$("p").toggle(); 

          /*If you want to know the current status of checkbox   go with below code*/
      if($(this).is(':checked')){
              $("p").show();
      }else{
              $("p").hide();
      }
  })

答案 1 :(得分:2)

实际上你根本不使用复选框类。这就是为什么它不起作用。

如下所示: -

更改 -

$('#myonoffswitch.onoffswitch').is(":checked"), function() {

$('.onoffswitch-checkbox').click(function() {

一切都会正常。

工作示例: - https://jsfiddle.net/2uz0rsq8/

注意: - 您可以使用: - $('.onoffswitch-checkbox').change(function(){(@NikhilNanjappa)