简体   繁体   English

用于选择父级兄弟姐妹的 JQuery 快捷方式

[英]JQuery shortcut to select siblings of parent

At the moment I'm using this目前我正在使用这个

$('body').on('click', '#edit_card .ui.menu a.item', function() {
  tab = $(this).closest('.ui.tab.active');
  updateRelationshipsContentCard(tab);
});

To try to select the active tab when clicking the a tag, but it is not finding anything, where is my mistake?单击 a 标签时尝试选择活动选项卡,但没有找到任何内容,我的错误在哪里?

<div class="ui pointing secondary menu">
    <a class="item" data-tab="1">1</a>
    <a class="item active" data-tab="2">Pessoas</a> <- Clicked this
</div>
<div class="ui tab" data-tab="1">
    <div class="ui basic segment">
    </div>
</div>
<div class="ui tab active" data-tab="2"> <- Need to select this
    <div class="ui basic segment">
    </div>
</div>

I know that using我知道使用

tab = $(this).parent().parent().children('.ui.tab.active');

Worked, but I can't see why using closest wouldn't工作,但我不明白为什么使用closest不会

The .closest() method will attempt to select any ancestor element that matches the selector that is provided. .closest()方法将尝试选择与提供的选择器匹配的任何祖先元素。 In other words, it will traverse up the DOM tree and search for an ancestor or parent element that matches the provided selector.换句话说,它将遍历 DOM 树并搜索与提供的选择器匹配的祖先或父元素。

It wasn't working in your case because .ui.tab.active isn't an ancestor of the clicked .item element.它在您的情况下不起作用,因为.ui.tab.active不是单击的.item元素的祖先。

If you want to use the .closest() method, you could use it to select the closest .ui.menu element, and then from there select the sibling .ui.tab.active element:如果你想使用.closest()方法,你可以用它来选择最近的.ui.menu元素,然后从那里选择兄弟.ui.tab.active元素:

$(this).closest('.ui.menu').siblings('.ui.tab.active')

Based on your code snippet, you could probably also select the closest #edit_card ancestor element and then use .find() to select the active tab:根据您的代码片段,您可能还可以选择最近的#edit_card祖先元素,然后使用.find()选择活动选项卡:

$(this).closest('#edit_card').find('.ui.tab.active')

..or since the .ui.menu element is a direct parent, you could merely use the .parent() and .siblings() methods together (assuming the markup doesn't change): ..或者因为.ui.menu元素是直接父元素,你只能一起使用.parent().siblings()方法(假设标记没有改变):

$(this).parent().siblings('.ui.tab.active')

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

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