2010-08-27 156 views
3

我有一个dividarticle_50。 如果我选择article_50内部的.title元素,我可以执行以下操作: $("#article_50 .title")如何用一个选择器选择一个jQuery元素的子元素?

现在说我要选择的是相同的标题,但是点击事件中:

$("#article_50").click(function(){ 
    $(this).children(".title").hide(); 
}); 

现在,我只好打电话给children方法来选择.title元素。 我可以在同一个选择器内选择它吗,而不需要拨打children

事情是这样的:

$("this .title").hide();

谢谢!

回答

8

几乎有:

$(".title", this).hide(); 
+1

+1为正确的答案,但我认为它比$(this).children(“。title”)的“可读性”更低。 – mathieu 2010-08-27 21:35:10

1
$("#article_50").click(function(){ $(".title", this).hide(); }); 
0

你不应该只能够说:

$("#article_50").click(function(){ $("#article_50 .title").hide(); }); 

这几乎是相同的,你不需要调用孩子。

+0

绝对,但如果不是一个特定的ID我有一个类,并在页面中的该类的几个元素,我会被迫使用'this'来标识它。虽然好点! – 2010-08-27 17:07:35

1

如果.title元素实际上是this的子元素,则使用.children()

当你这样做:

$(".title", this).hide(); 

... jQuery有运行7次或8测试中,它计算出你正在寻找.titlethis内部之前。

然后jQuery的只是将其翻转绕成这样:

$(this).find('.title') 

...,然后重新开始。因此,在所有测试之后,它都会调用一种方法。正如你所看到的那样效率不高。

另外,因为.children()只看起来深一层,所以如果您的元素实际上是一个孩子,则使用.children().find()更快。


编辑:

更快的方法是将缓存#article_50元素的变量,所以你并不需要创建一个jQuery对象为每次点击一次$(this)

var $art_50 = $("#article_50").click(function(){ 
    $art_50.children(".title").hide(); 
}); 

// Now you have a variable that you can use outside the click handler as well 
// in case you are selecting it elsewhere in your code.