开发者

Why is my $.each call returning more results than there are elements?

I'm having trouble doing a simple iterate through divs of a particular class.

There's two divs, but I'm getting 14 iterations.

  $(fun开发者_运维技巧ction() {
      $.each("div.container", function(){
         alert( "test" );
      });
   });

and the html

<div id="div1" class="container">

</div>

<div id="div2" class="container">

</div>

can anyone explain what i'm doing wrong? Thanks ahead


try this

$(function() {
      $("div.container").each( function(){
         alert( "test" );
      });
   });


You should use the following:

$(function() {
    $("div.container").each( function(){
        alert( "test" );
    });
});

There is a big difference between $.each and .each.

The first method is a generic iterator function that is used for iterating over arrays and objects, where the latter method is used for cycling through a collection of jQuery objects.

When you are calling $.each('div.container'), you are actually passing each letter of the string as the function argument. Since div.container contains 13 (yes, 13) characters, the iteration is called 13 times (see example).


 $(function() {
      $.each($("div.container"), function(){
         alert( "test" );
      });
 });


If you want to use $.each()

You have to put the jquery objects in the parameter but not the selector text

      $(function() {
      $.each($("div.container"), function(){
         alert( "test" );
      });
   });


$('div.container').each(function () {
    alert('test');
});

That's all you need really, haha. ;D

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜