gpt4 book ai didi

javascript - jQuery 两个选项卡容器使用相同的代码,如何仅在单击的容器内执行事件?

转载 作者:行者123 更新时间:2023-11-28 15:22:38 24 4
gpt4 key购买 nike

我希望能够将两个相同的(唯一不同的是选项卡 ID)选项卡容器与同一 block jQuery 一起使用。

我几乎让它工作了,但我的问题是,只要我从其中一个选项卡框(选项卡框一和选项卡框二)中单击一个选项卡,另一个容器的内容就会隐藏。

我想我需要在某个地方使用 $this,或者创建一些变量,因为我在重复我的代码(DRY,我知道我知道..)

关于如何不使两个选项卡框相互影响的任何建议?我已经尝试了几个小时,但我无法理解它..

代码笔:

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

代码:

// 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;
});

谢谢! :-)

最佳答案

减少代码。你可以减少它更多..

$(".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;
});

更新:
根据@nevermind 评论可以进一步减少

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;
});

关于javascript - jQuery 两个选项卡容器使用相同的代码,如何仅在单击的容器内执行事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32246957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com