简体   繁体   中英

jQuery conditional addClass not working

Having a little hang up with jQuery addClass. I have a #story div in my markup that shrinks down when it acquires the "away" class, and then pops back up when it looses that class.

Here's the snag:

$('#story div.x').on('click', function () {
  if (!$('#story').hasClass('away')) {
    $('#story').addClass('away');
  }
});

The code above simply adds a blank class="" to my story element, but...

$('#story div.x').on('click', function () {
  if (!$('#story').hasClass('away')) {
    setTimeout(function () {
      $('#story').addClass('away');
    }, 1000);
  }
});

That code adds the appropriate class="away" attribute.

What gives?

It sounds like there is another event updating the class, or perhaps the element is not yet ready but becomes available after 1 second, perhaps after an ajax call or when the DOM is ready.

Could that be it?

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