jquery选择具有类的父类的第一个子类 [英] jquery select first child with class of a parent with class

查看:229
本文介绍了jquery选择具有类的父类的第一个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了 clone()

<div class="sector_order">

    <div class="line_item_wrapper">
    SELECT THIS DIV
    </div>

    <div class="line_item_wrapper">
    NOT THIS DIV
    </div>

</div>

我这样想:

var form1 = $(this)
    .parents('.sector_order')
    .children('.line_item_wrapper')
    .children().clone(true)

并获取内部div与类 line_item_wrapper ,但是当我尝试添加这个时,我得到一个空对象:

and get both inner divs with the class line_item_wrapper, but I get an empty object when I try with this addition:

children('.line_item_wrapper :first')

谢谢!

推荐答案

你的问题是你的选择器错误,有几种方式:

Your problems is that your selector is wrong, in a few ways:

parents()返回与传递给方法的选择器匹配的一个,两个或多个元素;限制自己使用第一个匹配的元素使用 nearest()(返回一个或没有与传入选择器匹配的元素)。

parents() returns one, two or many elements that match the selector passed to the method; to limit yourself to the first-matched element use closest() (which returns one, or no, elements that match the passed-in selector).

首次使用 children()方法会返回两个元素,因为它们与提供的选择器匹配拥有 class_item_wrapper 的类;你需要明确说明你想要哪两个,你可以使用:第一个选择器(或者 first()方法),或:第一个孩子选择器。

Your first use of the children() method returns both elements, since they both match the supplied selector and have the class of line_item_wrapper; you need to explicitly state which of the two you want, you can either use the :first selector (or the first() method), or the :first-child selector.

第二次调用 children()方法查找选择器匹配的第一个元素的子元素,这些元素不是似乎想要的。

The second call to the children() method finds the children of the first element matched by the selector, which you don't seem to want.

无论如何,如果你必须使用父母(从相同的 $(this)元素开始):

Anyway, if you must use the parent (starting from the same $(this) element):

var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first').clone(true);

或者:

var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first().clone(true);

或者:

var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first-child').clone(true);

或者坦率地说,这是一种更简单的方法(但这确实省去了父类名检查):

Or, frankly, a simpler approach (but this does dispense with the parent class-name check):

var form1 = $(this).prevAll('.line_item_wrapper:last');

或者:

var form1 = $(this).siblings('.line_item_wrapper').eq(0);

参考文献:

  • closest().
  • eq().
  • find().
  • :first.
  • :first-child.
  • first().
  • :last.
  • parents().
  • prevAll().
  • siblings().

这篇关于jquery选择具有类的父类的第一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆