jQuery 给这个孩子添加班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13114853/
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
add class to child of this
提问by user1311784
This code is not working. this+'>a'
isn't a valid syntax.
So, how can I add/remove a class in a child of this
? In this case an a
element.
此代码不起作用。this+'>a'
不是有效的语法。那么,如何在 的孩子中添加/删除一个类this
?在这种情况下是一个a
元素。
jQuery(function ($) {
$("nav.menu>ul>li").hover(
function () {
$(this+'>a').addClass("hover_triangle");//error
},
function () {
$(this+'>a').removeClass("hover_triangle");//error
});
});
I can't do nav.menu>ul>li>a
because will select all a
elements in menu.
我不能这样做,nav.menu>ul>li>a
因为会选择a
菜单中的所有元素。
回答by inhan
$(this).children('a').addClass('hover_triangle');
and with the full code:
和完整的代码:
jQuery(function($) {
$('nav.menu>ul>li').hover(function() {
$(this).children('a').addClass('hover_triangle');
},function() {
$(this).children('a').removeClass('hover_triangle');
});
});
回答by Brombomb
$('a', this)
allows you to look only inside of the this
object
$('a', this)
允许您只查看this
对象内部
jQuery(function ($) {
$("nav.menu>ul>li").hover(
function () {
$('a', this).addClass("hover_triangle");//error
},
function () {
$('a', this).removeClass("hover_triangle");//error
});
});
回答by Sushanth --
You can use .find()
您可以使用 .find()
$(this).find('> a').addClass("hover_triangle");
This will only access the immediate child elements of nav.menu>ul>li
这只会访问的直接子元素 nav.menu>ul>li
If you want to just select the immediate children .find('a')
will get even the nested anchors.. To avoid that you need to use either .find('> a')
or .children('a')
如果你只想选择直接的孩子.find('a')
甚至会得到嵌套的锚点..为避免这种情况,你需要使用.find('> a')
或.children('a')
回答by charlietfl
There are 2 methods to search for descendents of this
. Most have replied with find()
(and it is easier to read) but a jquery selector also can have a second arfument which is context
.
有两种方法可以搜索 的后代this
。大多数人都回复了find()
(并且更容易阅读),但 jquery 选择器也可以有第二个参数,即context
.
$('a', this)
is another syntax and is the same as $(this).find('a)
. Internallly jQuery will take the first case and use find()
anyway, but the syntax is valid and many use it
$('a', this)
是另一种语法,与$(this).find('a)
. 内部 jQuery 将采用第一种情况并find()
无论如何使用,但语法是有效的,许多人使用它
API Refrence: jQuery( selector [, context] )
API 参考: jQuery( 选择器 [, 上下文] )
回答by Reflective
$(this).find('a').addClass('hover_triangle')
- more common way bacause it is not necessary to be a direct child
$(this).find('a').addClass('hover_triangle')
- 更常见的方式,因为没有必要成为直系子女