简体   繁体   English

Jquery 添加和删除子类

[英]Jquery add and remove child classes

I am trying to show an X next to a tab on my page when the tab is clicked and I am having problems showing and hiding the X. between the tabs.我试图在单击选项卡时在页面上的选项卡旁边显示一个 X,但在选项卡之间显示和隐藏 X. 时遇到问题。 I am getting the parent tag from.我正在从中获取父标签。

$('.tabs .tab-links a').on('click', function(e) {
    var currentValue = $(this).parent('li')
});

My problem is that I have a span within that LI and I cannot seem to access that span that has the X in it我的问题是我在那个 LI 中有一个跨度,我似乎无法访问其中包含 X 的跨度

<div class="tabs">
  <ul class="tab-links">
    <li>
      <a href="#tab1">Official Rules</a>
        <span class="close hidden">X</span>
    </li>
    <li>
      <a href="#tab2">Privacy Policy</a>
      <span class="close hidden">x</span>
    </li>
    <li>
      <a href="#tab3">Support</a>
      <span class="close hidden">X</span>
    </li>
  </ul>
</div>

Is there a way to add the X with like a removeClass('hidden') when the link is clicked with in that LI tag ?当在 LI 标签中单击链接时,有没有办法像removeClass('hidden')一样添加 X ?

You can try using .next("span") to target the next A 's element (the SPAN )您可以尝试使用.next("span")来定位下一个A的元素( SPAN
but the best way is first refer to a parent and than find the desired selector:最好的方法是首先引用父级,然后找到所需的选择器:

.closest("li").find("span")

in your example:在你的例子中:

$('.tabs .tab-links a').on('click', function(e) {
    var $span = $(this).closest('li').find("span");
    $span.toggleClass("hidden"); // OR whatever you want to do with $span
});

So going first for .closest() allows you to (one nice day) change the inner HTML of the LI and still get that span even if it's not any more .next() to the clicked element.因此,首先使用.closest()允许您(美好的一天)更改LI的内部 HTML 并仍然获得该span即使它不再是.next()到单击的元素。

You can use jQuery's siblings and remove the class of an element您可以使用 jQuery 的siblings并删除元素的类

$('.tabs .tab-links a').on('click', function(e) {
    $(this).parents("ul").find("span").addClass("hidden");
   $(this).siblings("span").toggleClass("hidden");

}); 

Check JS fiddle检查 JS 小提琴

Check updated JS fiddle检查更新的 JS小提琴

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

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