2012-09-19 34 views
2

这使我疯狂......但我肯定错过了一些东西。如果跨度包含少于3个字符,则隐藏跨度父级与jQuery

所以HTML的样子:

<ul> 
    <li><span>Product spec name</span><span>232112412</span></li> 
    <li><span>Product spec name</span><span>cm</span></li> 
    <li><span>Product spec name</span><span>80 cm</span></li> 
    <li><span>Product spec name</span><span>75 cm</span></li> 
    <li><span>Product spec name</span><span>cm</span></li> 
</ul> 

所以我想达到的目标是隐藏在第二跨度包含小于或等于2个字符的列表元素。 我想过把它们放到一个变量中,循环遍历它们,如果当前项的长度小于或等于2,那么jQuery应该隐藏它的父项。

继承人的代码,我写道:

$(document).ready(function() { 
    var pspec = $('ul li span:nth-child(2)'); 

    for(i=0;i<pspec.length;i++) { 
     if($(pspec[i]).text().length <= 2) { 
      $(this).parent().hide(); 
     } 
    } 
}); 

但这种代码不会做的伎俩......我仍然认为自己是一个jQuery的初学者,所以请你会这么好心来帮我在这一个?

在此先感谢!

最良好的祝愿, 马特

回答

1

演示:http://jsfiddle.net/PFaav/

$(document).ready(function() { 
    $('ul li').filter(function() { 
    return $(this).find('span').eq(1).text().length <= 2; 
    }).hide(); 
}); 

如果更换

$(this).parent().hide(); 

$(pspec[i]).parent().hide(); 
+0

感谢您的代码将工作!这工作完美! –

1

你可以使用jQueryeach,而不是使用for和混合jQuery和JavaScript的,

$(document).ready(function(){ 
    var pspec = $('ul li span:nth-child(2)').each(function(){  
     if($(this).text().length <= 2) { 
      $(this).parent().hide(); 
      } 
    }); 
}); 
1

下面尝试,

$(document).ready(function(){ 
    $.each ($('ul li'), function (idx, el) { 
     var $span = $(this).find('span').eq(1); //2nd span 
     if ($span.text().length <= 2) { 
      $span.parent().hide(); 
     } 
    }); 
}); 
1

使用过滤功能

$('ul li span:nth-child(2)').filter(function() { 
    return $(this).text().length < 3; // <-- get 2nd span elements whose text length < 3 
}).parent().hide();​ // <-- hide parent elements of the returned elements 

http://jsfiddle.net/y9dSU/