gpt4 book ai didi

jquery - 优化jquery添加和删除类

转载 作者:行者123 更新时间:2023-12-01 04:52:51 26 4
gpt4 key购买 nike

一定有解决办法,但我无法理解。我的问题很简单,但不知道如何优化。

我有简单的选项卡导航代码(用于查看内容)

$(function(){
$('#tab_o_nas article').hide();
$('#tab-1').show();
$('#opcja-1').addClass('active_tab');

$('#opcja-1').click(function(){
$(this).addClass('active_tab');
$('#opcja-2').removeClass('active_tab');
$('#opcja-3').removeClass('active_tab');
$('#opcja-4').removeClass('active_tab');
$('#tab_o_nas article').hide();
$('#tab-1').show();
return false;
});

$('#opcja-2').click(function(){
$(this).addClass('active_tab');
$('#opcja-1').removeClass('active_tab');
$('#opcja-3').removeClass('active_tab');
$('#opcja-4').removeClass('active_tab');
$('#tab_o_nas article').hide();
$('#tab-2').show();
return false;
});

$('#opcja-3').click(function(){
$(this).addClass('active_tab');
$('#opcja-1').removeClass('active_tab');
$('#opcja-2').removeClass('active_tab');
$('#opcja-4').removeClass('active_tab');
$('#tab_o_nas article').hide();
$('#tab-3').show();
return false;
});

$('#opcja-4').click(function(){
$(this).addClass('active_tab');
$('#opcja-1').removeClass('active_tab');
$('#opcja-2').removeClass('active_tab');
$('#opcja-3').removeClass('active_tab');
$('#tab_o_nas article').hide();
$('#tab-4').show();
return false;
});

});

fiddle

还有其他方法可以优化这个addClass和removeClass吗?获得更短的代码?

最佳答案

首先,您应该修复导航有序列表的标记( anchor 应该位于 <li> 内,而不是相反):

<ol id="nav_o_nas">
<li id="opcja-1"><a href="#">tab 1</a></li>
<li id="opcja-2"><a href="#">tab 2</a></li>
<li id="opcja-3"><a href="#">tab 3</a></li>
<li id="opcja-4"><a href="#">tab 4</a></li>
</ol>

然后,您可以向列表添加一个简单的 Binder ,该 Binder 委托(delegate)给 anchor ,查找单击的项目的索引,并适本地切换类和文章:

$('#nav_o_nas').on('click', 'a', function(e) {
e.preventDefault(); // should be used instead of return false;

// get the index of the clicked link (0-3)
var index = $('#nav_o_nas a').index(this);

// select all list items, remove the class, target the correct link, add the class
$('#nav_o_nas li').removeClass('active_tab').eq(index).addClass('active_tab');
// hide all articles, show the correct article
$('article').hide().eq(index).show();
});

在这里查看它的工作http://jsfiddle.net/4AYMs/2/

关于jquery - 优化jquery添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17592118/

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