Reputation: 498
I have an HTML structure like this below:
List
<ol id="years">
<li class="2011">2011</li>
<li class="2012">2012></li>
<li class="2013">2013></li>
</ol>
News:
<div class="news 2011">Some News here</div>
<div class="news 2012">Some News here</div>
<div class="news 2013">Some News here</div>
I am in need of a short-hand code of the code below(It works, but i want it to be automated, not manual):
$('.2011').click(function() {
$(".news").show().not('.2011').hide()
return false;
});
$('.2012').click(function() {
$(".news").show().not('.2012').hide()
return false;
});
$('.2013').click(function() {
$(".news").show().not('.2013').hide()
return false;
});
What i tried was:
for(i=2011; i<= 2020; i++){
$('.'+i+'').click(function() {
$(".news").show().not('.'+i+'').hide();
return false;
});
}
When i click on a li item, it just hides everything, so it is not the expected result.
Any help is appreciated. Thanks for your time!
Upvotes: 3
Views: 190
Reputation: 947
$('#years li').click(function(){
$('.news').show().not('.' + $(this).attr('class')).hide();
return false;
});
A better way is probably storing the year in a data attribute, eg:
<ol id="years">
<li class="2011" data-year="2011">2011</li>
<li class="2012" data-year="2012">2012></li>
<li class="2013" data-year="2013">2013></li>
</ol>
Then going:
$('#years li').click(function(){
$('.news').show().not('.' + $(this).data('year')).hide();
return false;
});
Then you avoid issues if you add other classes to the li items.
Upvotes: 5