2

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

所以 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 初学者,所以请你能帮我解决这个问题吗?

提前致谢!

最好的祝愿,马特

4

4 回答 4

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();
          }
     });
});
于 2012-09-19T15:23:48.340 回答
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();
        }
    });
});
于 2012-09-19T15:24:33.687 回答
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/

于 2012-09-19T15:26:23.503 回答
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();
于 2012-09-19T15:27:55.263 回答