简体   繁体   中英

jQuery Click function doesn't work on first child

jQuery Click function isn't working on first child of li becomes '.contracted' as on jsFiddle

<ul class="clearfix">
  <li class="contracted">
    <a href="#">
      <span>L1<b>: Recognize a digit represents 10 times the value</b></span>
    </a>
  </li>
  <li class="">
    <a href="#">
      <span>L2<b>: Recognize a digit represents 10 times the value</b></span>
    </a>
  </li>
</ul>

I tried to move click function at bottom as well. But it isn't working. Full working example is given in jsFiddle.

$('.contracted').click(function () {
  $(this).parent().attr('class', 'expanded');
  $('ul.expanded li.activeLesson').attr('class', 'selected');
  $('ul.expanded li:not(.selected)').attr('class', '');
});

Your $('.contracted').click(...) code will bind a click handler to any elements with that class at the moment that code runs - this will not automatically work on other elements that have the class added later. If you want it to work on any li element that has the contracted class at the time of the click use a delegated event handler set up via .on() :

$('ul').on('click', 'li.contracted', function() {
   ...
});

This binds the click handler to all ul elements, but then when a click occurs jQuery checks if the clicked item is a descendant of the ul which matches the selector in the second argument and only calls your function if it does.

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