简体   繁体   English

单击内部标签时将类添加到li

[英]add class to li when a tag inside is clicked

i want to add a class to the li when the tag is clicked i am using jQuery addclass but not sure how to get it to the LI 我想在单击标签时向li添加一个类,但是我正在使用jQuery addclass,但不确定如何将其添加到LI

<ul class="nav">
 <li class=""> <!---------add class to here---->
   <a href="default.asp">Home</a> <!-------- when this is clicked---->
   <ul>
       <li><a href="news.asp">link 1</a></li><!-------- but NOT when this is clicked----->
       <li><a href="news.asp">link 2</a></li>
       <li><a href="news.asp">link 3</a></li>
   <ul>
 </li>
 <li><a href="news.asp">News</a></li>
 <li><a href="contact.asp">Contact</a></li>
 <li><a href="about.asp">About</a></li>
</ul>

I hope this makes sense 我希望这是有道理的

Thanks in advance 提前致谢

You can achieve by adding following click function 您可以通过添加以下点击功能来实现

$("ul.nav > li > a").click(function(){
     $(this).parent().addClass("your_class");
});

For efficiency, you should use a single delegated event handler attached to your .nav element: 为了提高效率,您应该使用附加到.nav元素的单个委托事件处理程序:

If you want all the sibling element to remove that class use not . 如果您希望所有同级元素都删除该类,请使用not

eg 例如

    $('.nav').on('click', 'li > a', function(){
          var $li = $(this).parent();
          $li.siblings().not($li.addClass('smclass')).removeClass('smclass');
    });

Note: Answers with .nav > li (emphasis on > ) will only work for the top level links. 注意: .nav > li (强调> )的答案仅适用于顶级链接。 You need to clarify if you want the same behaviour on all links (which this example currently does). 您需要澄清是否要在所有链接上都具有相同的行为(此示例当前正在执行)。

If you only wanted it to work on the top-level links it would be 如果您只希望它在顶级链接上起作用,那将是

    $('.nav').on('click', '> li > a', function(){
          var $li = $(this).parent();
          $li.siblings().not($li.addClass('smclass')).removeClass('smclass');
    });

You can use immediate child selector to target all direct child elements: 您可以使用直接子选择器来定位所有直接子元素:

$('.nav > li > a').click(function(){
  $(this).parent().addClass('smclass')
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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