jQuery子元素选择器

4

I have the following markup:

<div class="form-fields">
  <div class="row">
    <span class="info">Info</span>
  </div>
</div>

如何使用子选择器选择 span.info?我已经尝试过:

$('.form-fields').children('.row .info')

但这对我没有用。

编辑:谢谢大家的答案。如果我将容器DIV分配为:

var parentDiv = $('.form-fields')

那么使用变量'parentDiv',最好的方法是选择 span.info

4个回答

9
使用find方法获取非直接后代元素:
$('.form-fields').find('.row .info')

2

为什么需要使用.children

$('.form-fields span.info')

@gstar:你最好使用“find”。 - SilentGhost

2

.children() 只会获取 直接的 子节点。您需要调用 .find()

$('.form-fields').find('.row .info')

甚至更多
$('.form-fields').find('.row').find('.info');

只需使用选择器

$('.form-fields .info')

Reference: .children(), .find()


0
$('.form-fields').children('.row').children('.info')

你可以像这样进行测试:

$(document).ready(function() {
    alert( $('.form-fields').children('.row').children('.info').length);


});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接