jQuery - How to group multiple variables when using show() or hide()?
How can I group all the following variables into using a sigle show() or hide() instead of individual call for 开发者_运维技巧each please? Thanks.
var alertsLink = "alertsLink";
var alertsLinkId = $j("#" + alertsLink);
var modifyLink = "modifySearch";
var events = $j("#eventsPanel");
var alerts = $j("#alertsPanel");
var results = $j("div.results");
if(id == eventsLink){
events.show();
alerts.hide();
results.hide();
eventsLinkId.hide();
alertsLinkId.show();
}else if(id == alertsLink){
events.hide();
alerts.show();
results.hide();
alertsLinkId.hide();
eventsLinkId.show();
}else if(id != modifyLink){
events.hide();
alerts.hide();
results.show();
alertsLinkId.show();
eventsLinkId.show();
}
}
Try this, jQuery supports multiple selectors:
$("#div1, #div2").show();
If you would like to keep using your variables, rather than litter your code with lots of magic strings, then you can do:
events.add(alertsLinkId).show();
alerts.add(results).add(eventsLinkId).hide();
You can combine selectors, like so:
$j("div.results, #alertsPanel")…
if(id == eventsLink){
$j("#eventsPanel, #alertsLink").show();
$j("#alertsPanel, div.results").hide();
}
You could do like this too :
$j('#eventsPanel, #alertsLink, #alertsPanel, div.results).hide();
switch (id)
{
case 'eventsLink': $j("#eventsPanel, #alertsLink").show(); break;
case 'alertsLink': $j("#alertsPanel").show(); break;
default: $j("div.results, #alertsLink").show(); break;
}
Keeping your if/else works too ;)
精彩评论