如果跨度包含少于3个字符,则使用jQuery隐藏span parent

时间:2012-09-19 15:21:13

标签: javascript jquery html text contains

这让我疯了......但我肯定会错过一些东西。

所以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>

所以我想要实现的是隐藏第二个span包含小于或等于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初学者,所以请你能帮我解决这个问题吗?

提前致谢!

祝福, 马特

4 个答案:

答案 0 :(得分:1)

您可以使用jQuery each代替使用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 :(得分: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();
        }
    });
});

答案 2 :(得分: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/

答案 3 :(得分: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();
相关问题