Jquery 选择器:jquery 函数,它改变包含“quit”的“
给出以下 html 代码:
<ul>
<li>
<a href="somelink">
<span class='someIconCss'></span>
<span>home</span>
</a>
</li>
[possibly some more <li></li>]
<li>
<a href="somelink">
<span class='someIconCss'></span>
<span>quit</span>
</a>
</li>
[possibly some more <li></li>]
</ul>
我想要一个 jquery 函数来更改包含“退出”链接的
的样式。 现在,我有以下内容:jQuery("li > a > span > span:contains('quit')").parent().parent().parent().attr("style", "float:right");
但我很确定有更好的方法。 问题是 jQuery("li > a > span > span:contains('quit')")
返回 span 元素而不是
最具可读性的答案获胜...
Given following html code:
<ul>
<li>
<a href="somelink">
<span class='someIconCss'></span>
<span>home</span>
</a>
</li>
[possibly some more <li></li>]
<li>
<a href="somelink">
<span class='someIconCss'></span>
<span>quit</span>
</a>
</li>
[possibly some more <li></li>]
</ul>
I would like to have a jquery function which alters the style of the <li>
containing the 'quit' link.
For now, I have the following:
jQuery("li > a > span > span:contains('quit')").parent().parent().parent().attr("style", "float:right");
but I'm pretty sure there is a better way.
Problem is that jQuery("li > a > span > span:contains('quit')")
returns the span element in stead of the <li>
Most readable answer wins...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
.has()
或走另一条路并使用
.closest()
:更容易理解的可能是
a:contains("quit")
,因为更清楚地表明您的意思是退出链接...You can use
.has()
or go the other way and use
.closest()
:More understandable might also be
a:contains("quit")
, as it is clearer that you mean the quit link...如果您知道“quit”一词不能出现在其他地方:
因为
contains
检查所有后代,而不仅仅是子代。工作演示位于 http://jsfiddle.net/alnitak/r8yBb/
If you know the word 'quit' can't appear anywhere else:
since
contains
checks all descendants, not just children.Working demo at http://jsfiddle.net/alnitak/r8yBb/
您需要
:has()
选择器:请注意,我'我们还使用了
css
方法来设置样式。You need the
:has()
selector:Note that I've also used the
css
method for setting the style.根据您的原始代码:
将为您提供包含的
元素。
Based on your original code:
will give you the containing
<li>
element.看看这个:
Check this out: