jQuery Each() function not working
I'm trying to add a class to each div.banner inside of my #destaques, but isn't working. What's happening?
JS:
$(document).ready(function() {
bannerRotator("#destaques");
});
function bannerRotator(element) {
// Conta quantos banners existem:
i = 0;
$(element).find(".banner").each(function() {
开发者_如何学C i++;
$(this).addClass("test");
});
alert(i);
//
}
HTML:
<div id="destaques">
<div class="banner"><img src="images/001.jpg"/></div>
<div class="banner"><img src="images/002.jpg"/></div>
<div class="banner"><img src="images/003.jpg"/></div>
</div>
addClass
will work on a collection automatically.
$("#destaques").find(".banner").addClass("test");
Example on jsfiddle.
side note: this could be also be simplified to
$("#destaques .banner").addClass("test");
Try this
jQuery.each($("div.banner"), function() {
i++;
$(this).addClass("test");
});
But if you just want to add the class you can also do it in the following one liner
alert($('div.banner').addClass("test").length);
精彩评论