当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery Two Tab Containers Using Same Code, How do I Excecute Event Only Inside Clicked Container?

问题描述:

I want to be able to use two identical (only difference are the tab ID's) tab containers with the same piece of jQuery.

I almost got it working, but my problem is that as soon as I click on a tab from one of the Tab boxes (Tab Box One & Tab Box Two), the content of the other container hides.

I think I need to use $this somewhere, or perhaps create a few variables, since I'm repeating my code (DRY, I know I know..)

Any advice on how to not make the two Tab Boxes affect each other? I've tried for hours, but I can't wrap my head around it..

Codepen:

http://codepen.io/StrengthandFreedom/pen/xwKENJ?editors=101

Code:

// Hide content info from all divs

$(".tabContent").hide();

// Show tabContent from the first child of each Tab Box

$(".tabContent:first-child").show();

// Add active class to first list item tab of each Tab Box

$("ul.tabs li:first-child").addClass("active").show();

$("ul.tabs li").click(function() {

// Remove active class on last child

$("ul.tabs li:last-child").removeClass("active")

$(this).prev().removeClass("active");

$(this).next().removeClass("active");

// Add class active to the one clicked

$(this).removeClass("active");

$(this).addClass("active");

// This need to hide only the content of the clicked div

$(".tabContent").hide();

var activeTab = $(this).find("a").attr("href");

$(activeTab).fadeIn(1500);

return false;

});

Thank you! :-)

网友答案:

Reduced code. You can reduce it more..

$(".tabContent").hide();
$(".tabContent:first-child").show();
$("ul.tabs li:first-child").addClass("active").show();
var tabs= $("ul.tabs li");
tabs.click(function() {

    tabs.removeClass("active")
    $(this).addClass("active");
    $(".tabContent").hide();
    var activeTab = $(this).find("a").attr("href");
    $(activeTab).fadeIn(1500);
    return false;
  });

Update:
as per @nevermind comment It can be reduce further

tabs.click(function() {
    tabs.removeClass("active")
    $(this).addClass("active");
    // $(".tabContent").hide(); 
    var activeTab = $(this).find("a").attr("href");
    $(activeTab).fadeIn(1500);
    $(activeTab).siblings().hide();
    return false;
  });
网友答案:
You can use event.target 
event.target
<div id='1'/>
<div id='2'/>

in js function you can do like this
if(event.target.id =='1'){
// code goes here
}
else if(event.target.id='2'){
//code goes here
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: