开发者

How to select a jQuery element's child with one selector?

I have an div with the id article_50. If I were to select the .title element inside article_50开发者_开发百科, I could do the following: $("#article_50 .title").

Now say I want to select that same title, but within a click event:

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

Now I had to call the children method to select that .title element. Could I select it within the same selector without the need to call children?

Something like this:

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

Thanks!


Almost there:

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


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


Use .children() if the .title element is actually a child of this.

When you do:

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

...jQuery has to run 7 or 8 tests before it figures out that you're looking for .title inside of this.

Then jQuery just flips it around into this:

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

...and starts over. So it is calling a method anyway after all that testing. As you can see it is not very efficient.

Also, because .children() only looks one level deep, it is faster to use .children() than .find() if your element is actually a child.


EDIT:

An even faster way would be to cache the #article_50 element in a variable, so you don't need to create a jQuery object for $(this) every time you click.

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.


Shouldn't you just be able to say:

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

That's nearly the same and you don't need to call children.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜