简体   繁体   中英

My javascript statement won't run its else statement even though checkbox isn't checked

I have a checkbox that should be being checked every time I click label. However, the js will only run the initial if statement. After that, when .menu-bar-checkbox.checked is false, the else statement won't run. And I am seeing the checkbox become checked.

So basically, after the label fades in, I can't also get it to animate on click afterwards. Thanks for the help!

My html:

<ul class="ul-links">
  <li class="hide li-portfolio"><a href="index.html" class="selected">Portfolio</a></li>
  <li class="hide"><a href="about.html">About</a></li>
  <li class="hide li-contact"><a href="contact.html">Contact</a></li>
</ul>
<label class="no-pull menu-bar">
    Menu
    <input class="menu-bar-checkbox" type="checkbox">
</label>    

My js:

$(function() {
    var $hide = $('.hide');
    $hide.hide();


    $('label').on('click', function() {

        if ($('.menu-bar-checkbox').checked = true) {
            $hide.fadeIn(1000);
        } else {
            $('.ul-links').animate ({
                height: 0,
            }, 1000)
        }

    });
})

Change:

($('.menu-bar-checkbox').checked = true)

to:

($('.menu-bar-checkbox')[0].checked == true)

Use == to check one value against another. And $('.menu-bar-checkbox') returns a list of checkboxes matching the class selection . (in your case only one). use [0] to address the correct one.

And completely in jQuery (as suggested in comments)

($('.menu-bar-checkbox').is(':checked'))

Note: the jQuery one will fire on every checkbox that has class .menu-bar-checkbox and is selected. The one with [0] will only fire on the first checkbox selected in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM