jQuery:根据动态添加的类选择一个元素?

时间:2017-08-19 15:53:10

标签: javascript jquery dynamic event-handling

我有一个非常简单的设置:

  • 按钮:在导航
  • 上切换“切换”类
  • li是子菜单的简化持有者:它应该在点击时更改aria属性,但仅当导航栏上有.toggled类时

但由于某种原因,这条线不起作用:

$('.toggled .has-children').on('click', function(e){

是否因为该类动态添加到父级?我怎么克服这个?

$(function() {
  

  var container = $('.nav');
  var button = $('.menu');
  
  //add remove class to nav
  button.on('click', function () {
      if(container.hasClass('toggled')) {
          container.removeClass('toggled');
      } else {
          container.addClass('toggled');
      }
  });

  // doesn't work?
  $('.toggled .has-children').on('click', function(e){
    e.preventDefault();
    $(this).attr('aria-expanded', 'true');
  })
  
});
.toggled {
  color: blue;
}

.has-children[aria-expanded=true] {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav class="nav"> 
<button class="menu">Menu</button>

  <ul>
    <li class="has-children" aria-expanded="false">
      Has children
    </li>  
    
  </ul>
  
</nav>

2 个答案:

答案 0 :(得分:1)

这不起作用,因为在添加切换类之前绑定了click事件。

您只应在添加切换后绑定点击次数:

$(function() {


  var container = $('.nav');
  var button = $('.menu');

  var addExpanded = function(){
    $('.toggled .has-children').unbind().on('click', function(e){
      e.preventDefault();
      $(this).attr('aria-expanded', 'true');
    })
  }

  //add remove class to nav
  button.on('click', function () {
      if(container.hasClass('toggled')) {
          container.removeClass('toggled');
      } else {
          container.addClass('toggled');
          addExpanded()    
      }
  });  
});

答案 1 :(得分:1)

如果能够基于 static 元素(例如body)使点击侦听器成为动态侦听器就足够了:

$('body').on('click', '.toggled .has-children', function(e){

见下面的工作演示:

&#13;
&#13;
$(function() {
  var container = $('.nav');
  var button = $('.menu');
  //add remove class to nav
  button.on('click', function() {
    if (container.hasClass('toggled')) {
      container.removeClass('toggled');
    } else {
      container.addClass('toggled');
    }
  });

  $('body').on('click', '.toggled .has-children', function(e) {
    e.preventDefault();
    $(this).attr('aria-expanded', 'true');
  })
});
&#13;
.toggled {
  color: blue;
}
.has-children[aria-expanded=true] {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
  <button class="menu">Menu</button>
  <ul>
    <li class="has-children" aria-expanded="false">
      Has children
    </li>
  </ul>
</nav>
&#13;
&#13;
&#13;