gpt4 book ai didi

javascript - 在 javascript 中用 switch/case 替换一堆显示/隐藏

转载 作者:行者123 更新时间:2023-11-29 22:41:23 25 4
gpt4 key购买 nike

页面中的菜单项将在“div class=foo”中用“div id=foo_(选定的菜单项)”替换“div id=foo_(当前菜单项)”

这就是我得到的,尽量减少你的早餐...

    $('#t1').click(function() {
$('#attorney').show();
$('#insurance,#financial,#estate,#trust,#death').hide();
});

$('#t2').click(function() {
$('#insurance').show();
$('#attorney,#financial,#estate,#trust,#death').hide();
});

$('#t3').click(function() {
$('#financial').show();
$('#attorney,#insurance,#estate,#trust,#death').hide();
});

$('#t4').click(function() {
$('#estate').show();
$('#attorney,#insurance,#financial,#trust,#death').hide();
});

$('#t5').click(function() {
$('#trust').show();
$('#attorney,#insurance,#financial,#estate,#death').hide();
});

$('#t6').click(function() {
$('#death').show();
$('#attorney,#insurance,#financial,#estate,#trust').hide();
});

最佳答案

Switch 语句有点难看。

var things = ['attorney', 'estate', 'insurance', 'financial', 'trust', 'death'];
var guide = {
t1: 'attorney', t2: 'estate', t3: 'insurance', t4: 'financial', t5: 'trust', t6: 'death'
};

$('#t1, #t2, #t3, #t4, #t5, #t6').click(function() {
var clicked = $(this).attr('id');
$.each(things, function(_, thing) {
var $thing = $('#' + thing);
if (guide[clicked] == thing) $thing.show(); else $thing.hide();
});
});

您还可以考虑使用 live() 设置事件处理程序,而不是直接在“t”对象上设置事件处理程序,无论它们是什么。如果可以为所有“事物”(律师等)指定一个类名,那也会更整洁,因为这样您就可以使用

快速将它们全部隐藏在点击处理程序中
   $('.thingClass').hide();

然后只显示适合被单击的选项卡的那个。然后它看起来像这样:

var guide = {
t1: 'attorney', t2: 'estate', t3: 'insurance', t4: 'financial', t5: 'trust', t6: 'death'
};
$('#t1, #t2, #t3, #t4, #t5, #t6').click(function() {
$('.thingClass').hide();
$('#' + guide[$(this).attr('id')]).show();
});

最后,您可能会考虑让可用的 jQuery 选项卡插件之一为您处理这一切:-)

关于javascript - 在 javascript 中用 switch/case 替换一堆显示/隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2534608/

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