问题
I have two DIV's. One has a list and the other has a collections of DIV's.
<div>
<ul>
<li><a>One</a></li>
<li><a>Two</a></li>
<li><a>Three</a></li>
</ul>
</div>
<div>
<div>Some content one</div>
<div>Some content two</div>
<div>Some content three</div>
</div>
When I click on the hyperlink 'One', I want to show the first DIV(Some content one) and hide all the other DIVs. When I click on the hyperlink 'Two', I want to show second DIV(Some content two) and hide all the others. How can I accomplish this using arrays in jQuery? Any other method is fine too.
Thanks for your time.
回答1:
$('li').click(function() {
var which = $(this).index();
$('div').find('div').hide().eq(which).show();
});
Working fiddle
回答2:
What the heck:
$('a').on('click', function(e) {
e.preventDefault();
$('div>div').eq($(this).closest('li').index()).show().siblings().hide();
});
FIDDLE
回答3:
change a little your html:
<div>
<ul>
<li><span data-showclass=".show_1">One</span></li>
<li><span data-showclass=".show_2">Two</span></li>
<li><span data-showclass=".show_3">Three</span></li>
</ul>
</div>
<div id="swichDiv">
<div class="show show_1">Some content one</div>
<div class="show show_2">Some content two</div>
<div class="show show_3">Some content three</div>
</div>
and then jQuery:
$('ul li span[data-showclass]').click(function(){
$('#swichDiv .show').hide().filter($(this).data('showclass')).show();
});
回答4:
Multi-line for unique row.
// show hide in jquery
$('.showdata').hide(); // hide all on start
$('.showhide').click(function (e) {
//e.preventDefault();
var SH = this.SH ^= 1; // "Simple toggler"
$(this).text(SH ? 'Hide' : 'Show')
var id = event.target.id; // get id
//alert(event.target.id);
$('#data' + id).toggle(); // show this one
});
<p><span class="showhide" id="1">Show</span> <span class="showdata" id="data1">content1</span> </p>
<p><span class="showhide" id="2">Show</span> <span class="showdata" id="data2">content2</span> </p>
回答5:
The simplest way is to give the div's and the anchors corresponding id's and class
Check this .. It can still be optimized
HTML
<div>
<ul>
<li><a id="wrapper1">One</a></li>
<li><a id="wrapper2">Two</a></li>
<li><a id="wrapper3">Three</a></li>
</ul>
</div>
<div class="wrap">
<div class="wrapper1" style="display:none">Some content one</div>
<div class="wrapper2" style="display:none">Some content two</div>
<div class="wrapper3" style="display:none">Some content three</div>
</div>
Javascript
$('[id^="wrapper"]').on('click', function(e) {
e.preventDefault();
$('.wrap > div').hide();
$('.'+ this.id).show();
});
Check Fiddle
来源:https://stackoverflow.com/questions/13186344/hide-or-show-specific-divs