将类添加到元素中此元素是子元素?

时间:2014-10-12 23:07:13

标签: javascript jquery addclass removeclass

我正在尝试向点击的li添加一个“active”类,但是在我的脚本中,我正在检索被点击的a,因为我想要检索“”的href。这样做的脚本是什么?

<ul class = "tab-links">
        <!-- Each tab is Anchored to its Contents -->
        <li class = "active"><a href ="#panel1">Panel 1</a></li>
        <li><a href ="#panel2">Panel 2</a></li>
        <li><a href ="#panel3">Panel 3</a></li>
        <li><a href ="#panel4">Panel 4</a></li>
</ul>



 <script type="text/javascript">
       $(function () 
  {

    //Listen for tab-links clicks
    $('.tab-panels .tab-links a ').on('click', function (e)
        {   
            //Remove current active panelToShow
            $('.tab-panels .tab-links li.active').removeClass('active');

            //Make panelToShow link active
            //??How do I addClass active to the li that was clicked on, when "this" refers to an "a" element?  
            //????$(this).addClass('active');
  ... })
   } 
 </script> ...

2 个答案:

答案 0 :(得分:0)

您使用parent

$(this).parent("li").addClass('active');

答案 1 :(得分:0)

您可以这样做:

$(this).parent('li').addClass('active');

这会将课程active添加到链接的最近父级li