我想在 .social-menu 中隐藏任何具有空白 href 的 LI。
我原来有:
$('ul.social-menu li a[href*=""]').hide();
但它只是隐藏了链接。
我想也许我可以使用:
$('ul.social-menu li a[href*=""]').addClass('hidden')
但它并没有添加隐藏的类。
HTML 是:
<ul class="social-menu">
<li class="facebook"><a target="parent" href=""></a></li>
<li class="twitter"><a target="parent" href="http://twitter.com/#!/dft_au">Twitter</a></li>
</ul>
最佳答案
使用the :has()
selector或 the has()
method选择所有 <li>
包含 anchor ( <a>
) 和空 href
的元素属性值:
$('ul.social-menu li:has(a[href=""])').hide();
// or…
$('ul.social-menu li').has('a[href=""]').hide();
请注意 .has()
比 :has()
更有效率: http://jsperf.com/jquery-has-vs-has虽然:has()
恕我直言,更具可读性。
关于javascript - 当 href 为空时隐藏 <li>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308211/