javascript jQuery addClass 到子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7933681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery addClass to a child element
提问by scferg5
I have the usual unordered list for a navigation menu with submenus...
我有一个带有子菜单的导航菜单的通常无序列表......
html:
html:
<ul>
<li><a href="#">Link 1</a></li>
<li>
<a href="#">Link with submenu</a>
<ul>
<li><a href="#">Sublink 1</a></li>
</ul>
</li>
</ul>
All of the links inside of the parent <li>
have a border radius. But if the parent <li>
has a child <ul>
, I don't want the link to have a radius.
父级内部的所有链接<li>
都有一个边界半径。但是如果父母<li>
有一个孩子<ul>
,我不希望链接有半径。
I'm currently using this jQuery:
我目前正在使用这个 jQuery:
<script>
$("li").has("ul").addClass("sub-radius");
</script>
It works fine except it's targeting the <li>
, but I need it to target the child <a>
and remove its radius.
它工作正常,除了它的目标是<li>
,但我需要它来定位孩子<a>
并删除它的半径。
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Ry-
Try this expression:
试试这个表达:
$("li:has(ul) > a").addClass("sub-radius");
Edit: If you don't want the sub-items to have border-radii, remove the >
in the query.
编辑:如果您不希望子项具有边框半径,请删除>
查询中的 。
回答by ?ime Vidas
You don't need jQuery here, you can achieve that with CSS alone. Just use the :only-child
pseudo-class:
此处不需要 jQuery,仅使用 CSS 即可实现。只需使用:only-child
伪类:
a:only-child { /* define border-radius here */ }
Live demo:http://jsfiddle.net/QYaqb/
现场演示:http : //jsfiddle.net/QYaqb/
回答by jdross
This should work for your HTML
这应该适用于您的 HTML
("li").has("ul").children("a").addClass("sub-radius");
回答by Alex Peattie
I think you want .find
:
我想你想要.find
:
<script>
$("li:has(ul)").find("a").addClass("sub-radius");
</script>
回答by Patricia
just need to find the a's inside the li:
只需要在 li 中找到 a:
$("li").has("ul").find('a').addClass("sub-radius");
here's a fiddle: http://jsfiddle.net/cBfMV/
这是一个小提琴:http: //jsfiddle.net/cBfMV/