0

我正在尝试做一个循环来使用类选择器检查所有元素。

我有

html

<div class='label'>aaaa</div>
<div class='label'>bbbb</div>
<div class='label'>cccc</div>
<div class='label'>dddd</div>

 var pre=$('.label')

    pre.each(function(e){
        console.log(e);
    })

但它不显示元素(aaaa,bbbb ..等)。

我该怎么做呢?非常感谢

4

2 回答 2

3
var pre = $('.label');

pre.each(function(i, el){
    console.log( el );
    // OR
    console.log( this ); // will give you the element

    // suppose to get text
    console.log( $(el).text() ); // or $(this).text()
});

演示

.each()is的第一个参数index和第二个参数是value (here your target element)

阅读更多关于.each().

于 2012-09-13T16:48:57.960 回答
1

为了回答,.eachjQuery中的方法在调用时传递了两个值(在上下文中):

.each(function(index,value){
});

所以我只e在你的每个函数中提供你只要求索引参数。您需要提供两个参数来获取实际的元素或值。

但是,当迭代元素时,交互函数的上下文也会传递给元素。所以:

$('.label').each(function(index,element){
  // element == this
});

因此,如果您不想提供第二个参数,您可以this在函数中引用。

于 2012-09-13T16:51:17.790 回答