这让我发疯了...但我肯定错过了一些东西。
所以 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初学者,所以请你好心地帮助我解决这个问题吗?
提前感谢!
愿你安好Matt
演示: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();
试试下面,
$(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();
}
});
});
使用过滤器函数
$('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/
使用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();
}
});
});