javascript - Using parent() three times, is there a better way? - Stack Overflow

I've got some code that looks like this:jQuery(this).parent().parent().parent().parent().next(&quo

I've got some code that looks like this:

jQuery(this).parent().parent().parent().parent().next(".results-table").css("display", "block");

Basically, after clicking a link inside of a table, the following results table will show, the problem is that this link is inside a td, which is inside a tr, which of course is inside a table, hence the repeated parent selector.

Is there a better way of doing this that I'm missing? I've not got lots of experience with jQuery unfortunately.

I've got some code that looks like this:

jQuery(this).parent().parent().parent().parent().next(".results-table").css("display", "block");

Basically, after clicking a link inside of a table, the following results table will show, the problem is that this link is inside a td, which is inside a tr, which of course is inside a table, hence the repeated parent selector.

Is there a better way of doing this that I'm missing? I've not got lots of experience with jQuery unfortunately.

Share Improve this question asked Sep 20, 2012 at 12:30 SeanSean 6,5099 gold badges49 silver badges70 bronze badges 2
  • 2 depending on your DOM, .parents("yourSelector") might work better – anderssonola Commented Sep 20, 2012 at 12:32
  • Could you add an example block of your table showing any classes or id's on elements? That would be more beneficial than explaining how your elements are layed out. – Jeff LaFay Commented Sep 20, 2012 at 12:33
Add a ment  | 

5 Answers 5

Reset to default 6

You can use jQuery(this).closest("table") http://api.jquery./closest/

jQuery(this).parents("table").next(".results-table").css("display", "block");

or

jQuery(this).closest("table").next(".results-table").css("display", "block");
jQuery(this).closest('table').css("display", "block");

or even

jQuery(this).closest('.results_table').css("display", "block");

dependent on your desired result and your HTML elements.

$(this).parents(":eq(3)")

This could be helpful

Or.. you could possibly make use of event delegation, such as .on() instead of .click(). Then, you can simply use e.delegateTarget.

For example,

$(parent).on("click", link, function(e) {
    jQuery(e.delegateTarget).next(".results-table").css("display", "block");
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745405082a4626278.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信