简体   繁体   English

选项卡式内容不适用于多个div

[英]Tabbed content won't work with multiple divs

I'm new to Javascript and am working on the following: 我是Java语言的新手,正在从事以下工作:

$('.tabs-holder li').click(function () {
    var tabID = $(this).attr('data-tab-id');
    $(this).closest('.tabbed-content').find('.tabs-holder li').removeClass('active');
    $(this).addClass('active');
    $(this).closest('.tabbed-content').find('.content-holder').children('.tab-content').removeClass('active').siblings('.tab-content[data-tab-id=' + tabID + ']').addClass('active');
});

I'm trying to get it to work on all divs with a data-tab-id of the same value, but it's only acting on the one div. 我试图让它在具有相同值的data-tab-id的所有div上工作,但它仅作用于一个div。

JSFiddle here http://jsfiddle.net/dynaf9pc/8/ JSFiddle在这里http://jsfiddle.net/dynaf9pc/8/

That content container you're trying to target is a sibling of .tabbed-content so you need to back out to the parent .tabbed-content and then navigate to its sibling like so: 您要定位的内容容器是.tabbed-content的同级对象,因此您需要返回到父.tabbed-content ,然后按以下方式导航至其同级对象:

   $(this).closest(".tabbed-content")
          .siblings(".content-holder")
          .find('.tab-content[data-tab-id=' + tabID + ']')
          .addClass('active')
          .siblings()
          .removeClass('active');

Also I refactored some of your JS that was redundant and made it shorter by chaining your selectors: 我还重构了一些多余的JS,并通过链接选择器使其变得更短:

FIDDLE 小提琴

You are not iterating through the elements. 您没有遍历所有元素。 If you add each(), it will go through multiple div's that it will find. 如果添加each(),它将遍历将找到的多个div。

$('.tabs-holder li').click(function () {
    var tabID = $(this).attr('data-tab-id');
    $(this).closest('.tabbed-content').find('.tabs-holder li').removeClass('active');
    $(this).addClass('active');
    $(this).closest('.tabbed-content')
        .find('.content-holder')
        .children('.tab-content')
        .removeClass('active')
        .siblings('.tab-content[data-tab-id=' + tabID + ']')
        .each(function() {
            $(this).addClass('active');
        })
});

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

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