定位一个空的< li> [英] Target an empty <li>
问题描述
我知道对于jQuery专家来说,这一定是一个简单的方法,但是老实说,我不知道如何实现.
I know this one must be a simple one for the jQuery gurus here, but I honestly have no idea how to accomplish it.
我有以下HTML:
<div class="panel_contents">
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li></li>
<li></li>
</ul>
</div>
我需要定位空的<li>
并为其添加一个类,例如 class ="empty" .如果不需要,我不想修改HTML以手动添加类以用于演示目的.
I need to target the empty <li>
and attach a class to them, for example class="empty". I don't want to modify the HTML to manually add the classes for presentational purposes if I don't have to.
出于演示目的,我在此处启动了 JSFIDDLE .
I started a JSFIDDLE here for demo purposes.
感谢您对此提供的任何帮助.
Thanks a million for any help with this.
-
编辑3 [9/16/14]
今天,我承认也许真的没有必要使用jQuery,因为可以使用:empty
伪选择器以CSS为空元素定位空白元素,实际上,从IE8到所有浏览器都很好地支持它(尽管部分支持)- http://caniuse.com/#search=empty
Today, I admit that maybe using jQuery might not be really necessary since empty elements can be targeted with CSS using the :empty
pseudo-selector, which is actually quite well supported across all browsers all the way down to IE8 (albeit partial support) - http://caniuse.com/#search=empty
编辑2
这是 另一种解决方案 .
此解决方案在<li>
中查找<a href>s
,如果有,则不会添加该类,如果没有<a href>s
,则添加该类 empty .
This solution looks for <a href>s
inside the <li>
, if it has one, it will NOT add the class, if there are no <a href>s
, then the class empty is added.
编辑1
感谢Daniel的解决方案.这是 工作演示
Thanks to Daniel for the solution. Here's a WORKING DEMO
推荐答案
使用:empty
伪选择器.
$('li:empty').addClass('empty')
这篇关于定位一个空的< li>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!