jquery 这个子选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4487992/
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 child selector?
提问by matt
hey, quick question, i couldn't find anything on the web. I have a parent div and a child div inside of it. to select it with css you would say:
嘿,快速提问,我在网上找不到任何东西。我里面有一个父 div 和一个子 div。用 css 选择它,你会说:
#parent .child {}
In jquery I have a var for my parent element, however how can i select the child with this? I know it's easy to create a new var, i'm just curious if it's possible?
在 jquery 中,我的父元素有一个 var,但是如何选择子元素呢?我知道创建一个新的 var 很容易,我只是好奇是否有可能?
var Parent = $('#parent');
Parent.click(function() {
$(this > '.child').hide();
thank you
谢谢你
回答by Gabi Purcaru
The correct syntax is:
正确的语法是:
$(".child", this)
If you only want the directchildren:
如果你只想要直接的孩子:
$("> .child", this)
(credit goes to Gumbofor mentioning this)
(感谢Gumbo提到了这一点)
Update, two years later:
两年后更新:
You can use $(this).find('> .child')
您可以使用 $(this).find('> .child')
回答by jAndy
You may just invoke the .find()
method:
您可以只调用该.find()
方法:
var Parent = $('#parent');
Parent.click(function() {
$(this).find('.child').hide();
});
If you only want to select the immediate children, use the .children()
method instead:
如果您只想选择直接子级,请改用该.children()
方法:
Parent.click(function() {
$(this).children('.child').hide();
});
People often use a syntax like
人们经常使用这样的语法
$('.child', this);
aswell. It's not very convinient to me since you write a "reverse" order someway. Anyway, this syntax gets converted internally into a .find()
statement, so you're actually saving a call.
还有。这对我来说不是很方便,因为您以某种方式编写了“反向”顺序。无论如何,此语法在内部转换为.find()
语句,因此您实际上是在保存调用。
Ref.: .find(), .children()
回答by Mohan Ram
U can find children of your parent elements and apply css.
您可以找到父元素的子元素并应用 css。
Sample code is below.
示例代码如下。
var Parent = $('#parent');
Parent.click(function() {
$(this).find('.child').hide();});
回答by AEMLoviji
try this code:
试试这个代码:
$("#parent").click(function () {
$(this).next().hide();
});
回答by Anwar Chandra
var Parent = $('#parent');
Parent.click(function () {
$(".child", this).hide();
});
or
或者
$("#parent").click(function () {
$(".child", this).hide();
});