开发者

jQuery Each() function not working

开发者 https://www.devze.com 2023-02-19 14:14 出处:网络
I\'m trying to add a class to each div.banner inside of my #destaques, but isn\'t working. What\'s happening?

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消