问题描述:

I can't figure it out why is this not working:

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

if ($('#check').is(':checked')) {

$('p').hide();

} else {

$('p').show();

}

});

</script>

</head>

<body>

<input type="checkbox" id="check" />

<p>If you click on the checkbox, I will disappear.</p>

</body>

</html>

Fiddle

When i click on the checkbox it should hide the p tag but it doesn't...

This should be so simple, but then again it is not :(

网友答案:

You're only running your code on load of the page. You need to add a change event handler to your checkbox. Also note that you can simplify the code by passing the checked property value to the toggle() method:

$(document).ready(function() {
  $('#check').change(function() {
    $('p').toggle(!this.checked);
  }).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check" />
<p>If you click on the checkbox, I will disappear.</p>
网友答案:
Try it
//  for protect global scope use closure
(function ($) {
  // document ready
  $(function(){
     // use prop method for checkbox
     if ( $('#check').prop( "checked" ) ) {
       $('p').slideToggle(250);
     }
  });
}(jQuery));
网友答案:

I updated your jsfiddle to work & makes use of the jquery .change function.

$(document).ready(function(){

    $('#check').change(function() {
        if ($('#check').is(':checked')) {
            $('p').css("display","none"); 
        }
        else {
            $('p').css("display","block");
        }
    });
});

https://jsfiddle.net/d7d2n0x4/2/

相关阅读:
Top