jQuery - 使用not()选择器

时间:2013-05-03 16:28:02

标签: jquery

我是学习jQuery的初学者,问题是:

  

使用“not”内置函数,为所有不包含UL元素的LI元素设置“text-decoration”CSS属性为“underline”。

我尝试过几种不同的选择器,包括:

$(li:not(li > ul)).css('text-decoration','underline');
$(li:not(li ul)).css('text-decoration','underline');

任何人都可以帮助我吗?感谢。

3 个答案:

答案 0 :(得分:3)

使用not()函数尝试此操作:

$('#myDemo > li').not(':has(ul)').css('text-decoration','underline');

#myDemo是最顶层ul ID

FIDDLE

答案 1 :(得分:1)

上面给出的answer从不工作。查看fiddle以了解原因,并获得答案


<强>说明

这是一个棘手的事情。解决方案可能看似简单,但可能无效 通过检查<li>是否没有<ul>而返回<li>的任何尝试都将是徒劳的。

这是因为拥有<ul>的{​​{1}}人<li><ul><li>。所以,即使你有无与伦比那些<li>,你也已成功匹配他们的孩子 - 最里面<li> s 。 最后,您已匹配DOM中的所有<ul>

要更好地理解它,请查看以下JS Fiddle,包括答案


答案 - 来自小提琴

我觉得你必须使用额外的过滤器(建议欢迎)。 IMO可以通过引用最大父$('li').not(':has(ul)').css('text-decoration','underline'); // Matches all the LIs, and therefore not useful $('li').filter(function() { return $('ul', this).length == 0; }).css('color', 'blue'); // Nice try, but still Matches all the LIs // This works, but need a reference to main parent, using a class, id etc. $('li').not(':has(ul)').filter(function() { return $(this).parent().hasClass('the-parent'); }).css('color', 'red'); ,通过类或ID,然后过滤结果来完成

{{1}}

答案 2 :(得分:0)

我不确定你是否可以只选择一个选择器。

这应该有效:

$('li').each(function() {
    if($(this).children('ul').length == 0) {
        $(this).css('text-decoration','underline');
    }
});