在jQuery中通过类内部元素选择项目

selecting items by class inside element on jQuery

本文关键字:内部 元素 选择 项目 jQuery      更新时间:2023-09-26

我尝试在.dropzone父元素中选择所有.preview子元素。

$('.dropzone').add($('.preview')).length

返回3,但有2个对象。我猜它也计数.dropzone容器。

如何只选择两个.preview项?

请尝试此演示:http://jsfiddle.net/KjJZx/1/ http://jsfiddle.net/wbkVS/

API: http://api.jquery.com/children/Get the children of each element in the set of matched elements, optionally filtered by a selector

希望它符合需要!:)

$('.dropzone').children('.preview').length

Try

$('.dropzone').find('.preview').length

选择这个的通用选择器语法是:

$('.dropzone .preview').length or

$('.dropzone > .preview).length(如果它是.dropzone的直接子节点)

http://api.jquery.com/category/selectors/

@Igor的答案也很好

你是正确的,它也在计算容器div。使用jQuery函数中的CSS后代选择器(和元素之间的空白空间)来选择元素的后代(后代是元素内的所有元素)。

$('.dropzone .preview').length === 2

或者,如果你只想要孩子(直接后代),使用孩子选择器(>)。

$('.dropzone > .preview').length === 2

add函数在jQuery对象中添加当前元素,正如您所料。