0

我有一个列表,每个 li 都有一个数据角色编号。如果任何一个孩子 li 的数据角色数超过 50,我需要做点什么

到目前为止有这个,但它不工作

$('ul.chart').each(function(i) {
    var dataRole = $(this).data('role');

    if ($(this).children(dataRole < 51)) {
                alert('all of the children are below 50') 

    }else {
         alert('one or more of the children are above 50')              
    }                  
}); 
4

3 回答 3

3
$('ul.chart li').each(function(){
   if ($(this).data('role')>50) {
      alert('one or more of the children are above 50');
      return false; // stops the iteration
   }
});

使用过滤器(但它是等效的,并且在制作新集合时可能不会更快):

if ($('ul.chart li').filter(function(){ return $(this).data('role')>50 }).length) {
     alert('one or more of the children are above 50');
}

对于本杰明,使用every,您可以这样做

if (!$('li').get().every(function(e){ return $(e).data('role')<50 })) {
     alert('one or more of the children are above 50');
}
于 2013-05-23T11:04:27.840 回答
3

像这样的东西:

var over50 = $('ul.chart li').filter(function() {
    return $(this).data('role') > 50;
}).length > 0; 

这会选择<li>元素内的所有元素<ul class="chart">,然后仅过滤那些data-role属性值大于 50 的元素,然后检查结果对象的长度;如果大于 0,则至少存在一个元素。

然后你就可以if(over50) { doSomething() }用来执行你的条件逻辑。

于 2013-05-23T11:09:14.140 回答
0
if($('ul.chart li').filter(function(){return $(this).data('role') > 50;}).length > 0){
 // do something, one or more have data-role more then 50
}
于 2013-05-23T11:08:29.323 回答