2017-01-06 21 views
1

遇到麻烦检查length$.each()功能如何检查长度

假设我有2 elements这样每个函数内部,

<div class="demo"> 
    <!-- 30 -- with different class> 
    <input type="text" name="demo" class="hell"/> 
    <input type="text" name="demo2" class="seeHere"/> 
</div> 
$('.demo').find('input').each(function(){ 
    var $this = $(this); 
    if($this.find('.seeHere').length>0){ // throws error length of undifined 
    // do something 
    }else{ 
    // do something 
    } 
}); 

它抛出错误长度对于如果

至于第一次它将chache

<input type="text" name="demo" 
     class="hell"/> 

,有没有办法在jQuery的每个功能,$返回false内if(el.length>0 || return false) like el.push(value || 'No value')

请帮我在此先感谢

+0

要在'if'检查什么声明?我想你需要检查'类'不是那里的长度。 – vijayP

+0

所示的代码(不考虑缺少关闭的HTML注释)不会抛出关于“未定义的长度”的错误 - 您已经删除了太多真实代码或其他东西......并且没有发生“chache”操作 –

+1

您的代码不应该抛出提到的错误,但是'$ this.find('。seeHere')'将永远是一个长度为0的jquery对象。 –

回答

2

使用hasClass jQuery的

$('.demo').find('input').each(function(){ 
var $this = $(this); 
    if($this.hasClass('seeHere')){ 
    // do something 
    }else{ 
    // do something 
    } 
}); 

(这)类似于指数

我的意思是说

假设你有这样的事情

<div id="#a" class="abc"> 
<div id="#b" class="abc"> 
<div id="#c" class="abc"> 

所以,当你遍历“名为.abc”像

$(".abc").each(function() { 
     //Here $(this) resembles to $("#a") at first iteration 
     // $("#b") at second iteration 
     // $("#c") at third iteration 
}); 
1

你并不需要遍历什么 - 使用所需的选择器和.length属性来获取具有该类的元素的数量。

$(document).ready(function(){ 
 
var len = $('.seeHere').length; 
 
    console.log(len); 
 
//displays 2 in the console since there are two divs with the desired class 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="a" class="hell"> 
 
<div id="b" class="seeHere"> 
 
<div id="c" class="something"> 
 
<div id="d" class="seeHere">

,如果你想somethimg发生到具有一流的每一个元素 - 使用。每()方法上的选择:

$(document).ready(function(){ 
    $('.seeHere').each(function(){ 
     //do stuff 
     }); 
    });