开发者

replace a bunch of show/hide with switch/case in javascript

开发者 https://www.devze.com 2022-12-24 05:19 出处:网络
Page has menu items that would replace a \'div id=foo_(current menu item)\' with \'div id=foo_(selected menu item)\' in \'div class=foo\'

Page has menu items that would replace a 'div id=foo_(current menu item)' with 'div id=foo_(selected menu item)' in 'div class=foo'

Here's what I've got, and try to keep your breakfast down...

    $('#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();
    });

    $('开发者_如何学C#t6').click(function() {
        $('#death').show();
        $('#attorney,#insurance,#financial,#estate,#trust').hide();
    });


Switch statements are kind-of ugly.

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

You might also consider setting up the event handler with live() instead of directly on the "t" thingies, whatever they are. It would also be neater if all the "things" (attorney, etc) could be given a class name, because then you could just hide them all quickly in the click handler with

   $('.thingClass').hide();

and then just make the one visible that's appropriate for the tab that was clicked. Then it could look something like this:

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

Finally, you might consider letting one of the available jQuery tab plugins handle this whole thing for you :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消