jquery question - addclass to element depending on active image in rotating banner
EDIT : Per Slaks
$j('#banner-content img').each(function() {
var link = $j('#page-tabs li a.' + $j(this).attr('class'));
if ($j(this).is(':visible')) {
link.addClass('active');
} else {
link.removeClass('active');
}
});
ORIGINAL POST
I have a banner that rotates a series of three images. The active one has a display:block, while the inactive have display:none. I'm trying to match the class for the active image with an tag so that I can add an "active" class to the a tag. Having some trouble writing that function. It's adding all of the classes for each of the img elements, regardless of whether they're being displayed or not...
The html markup looks like this:
<div id="banner-area">
<div class="clearfix" id="promo-boxes-nav">
<ul id="banner-tabs">
<li>
<ul id="page-tabs">
&开发者_如何学Golt;li><a class="t39" href="#">1</a></li>
<li><a class="t42" href="#">2</a></li>
<li><a class="t49" href="#">3</a></li>
</ul>
</li>
<li class="last"> </li>
</ul>
</div>
<div id="banner-content">
<img class="t39" src="http://localhost:8888/1.png" style="position: absolute; top: 0px; left: 0px; display: none; opacity: 0;">
<img class="t42" src="http://localhost:8888/2.png" style="position: absolute; top: 0px; left: 0px; display: block; opacity: 1;">
<img class="t49" src="http://localhost:8888/3.png" style="position: absolute; top: 0px; left: 0px; display: none;opacity: 0;">
</div>
</div>
The function in its current form looks like this:
$j('#banner-content img').each(function() {
if($j(this).css('display','inline')) {
var bcClass = $j(this).attr('class');
$j('#page-tabs li a').each(function() {
if($j('#page-tabs li a').hasClass(bcClass)) {
$j(this).addClass(bcClass);
}
});
}
});
Answer for new question:
$j(this).show()
will show the element.
You mean
if($j(this).is(':visible'))
Also, in your selectors, you want to write $j(this)
, not $j('#banner-content img:visible')
.
Finally, the code will be easier to read if you make a separate variable to hold the <a>
element, like this:
var link = $j('#page-tabs li a.' + $j(this).attr('class'));
if ($j(this).is(':visible'))
link.addClass('active');
else
link.removeClass('active');
Answer for old question:
Your problem is that you're calling hasClass
on all of the links within the inner each
call. This will check whether any of the elements has that class, not just the current one.
You need to change it to if($j(this).hasClass(bcClass))
.
However, your code is needlessly complicated, and can be written much more simply:
$j('#page-tabs a.'
+ $j('#banner-content img:visible').attr('class'))
.addClass('active);
This code calls $j('#banner-content img:visible').attr
to find the class of the visible <img>
element, then puts the class directly into a jQuery selector.
Note that you probably also want to call removeClass
.
精彩评论