jQuery this 和 Selector $(this:first-child).css('color', 'red');
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3324622/
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 this and Selector $(this:first-child).css('color', 'red');
提问by hoerf
Is it possible to use a :selector
with the following in jQuery?
是否可以:selector
在 jQuery 中使用具有以下内容的a ?
$('.galler_attr').bind('click', function() {
$(this:first-child).css('color', 'red');
});
回答by Russ Cam
No. You're trying to mix the function context with a string.
不。您正在尝试将函数上下文与字符串混合。
Use this
as the contextof the selector or call find()
on $(this)
to search within the DOM scope of the element. Either
使用this
的情况下选择或调用find()
上$(this)
的元素的DOM范围内进行搜索。任何一个
$('.galler_attr').bind('click', function() {
$(this).find(':first-child').css('color', 'red');
});
or this (which resolves to the above internally):
或者这个(在内部解决上述问题):
$('.galler_attr').bind('click', function() {
$(':first-child', this).css('color', 'red');
});
回答by Muhit
Yes, you can use it but not in such a way. You can put it as Russ says.
是的,您可以使用它,但不能以这种方式使用。你可以像拉斯所说的那样。
$('.galler_attr').bind('click', function() {
$(this).find(':first-child').css('color', 'red');
});
You can get better help for such problems by going to www.visualjquery.com. It's pretty.
您可以通过访问 www.visualjquery.com 获得针对此类问题的更好帮助。这很美。
回答by Reigel
in that case, use .is()
在这种情况下,请使用 .is()
$('.galler_attr').bind('click', function() {
$(this).is(':first-child').css('color', 'red');
// this would change the color to red if the clicked element is a first-child....
});
I wonder why not just bind it to the first-child directly?
我想知道为什么不直接将它绑定到第一个孩子?
$('.galler_attr:first-child').bind('click', function() {
// this would bind click event to the first-child element...
$(this).css('color', 'red');
});