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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:14:27  来源:igfitidea点击:

jQuery this and Selector $(this:first-child).css('color', 'red');

jqueryselectorthis

提问by hoerf

Is it possible to use a :selectorwith 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 thisas 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');

});