是否可以使用’>’来选择’this’对象的子元素?

我面临的原始问题是这样的:

$('#setting-box > div').change(function(){ // Would like to select current div's span child and do something } 

我做了一些研究,发现这篇文章: 如何让$(this)选择器的孩子们?

这两种参数实际上对我有用

$('span', this).html($('input', this).val());

现在我的问题是,有没有任何方法可以选择这个span元素,

在$()中使用单个参数? (而不是使用像find(),child()等方法)

比如,是否有任何事情/方式来做$(this > childElement)

谢谢你的帮助

要直接回答你的问题,没有一种方法可以在jQuery中搜索this元素的子元素。 那是因为jQuery的默认上下文是整个文档,所以要改变它,除了选择器之外你还需要使用一些额外的代码。

此外,DOM元素本身(在您的示例中的this变量中)不能进入选择器,因为选择器是一个字符串,并且DOM元素没有任何方式在选择器字符串中表达它。 因此,您必须使用额外的参数来限定为选择器搜索的范围,而不仅仅是文档。

因此,为了限制选择器搜索的范围,您可以选择听起来像您可能已经知道的选项:

 $(this).find(selector) // any descendant $(selector, this) // any descendant $(this).children(selector) // only look at direct children 

如果我想要任何后代,我自己更喜欢使用.find()因为我认为代码更直接可读。 所以,为了你的特殊需要,我会用它:

 var self = $(this); self.find("span").html(self.find("input").val()); 

或者,如果只是直接的孩子:

 var self = $(this); self.children("span").html(self.children("input").val()); 

此外,您的.change()代码应绑定到实际支持该事件的元素,该元素类似于 ,而不是常规的

你可以使用find() :

 $('#setting-box > div').change(function(){ $(this).find('span').html($('input', this).val()); }); 

如果您不想使用find使用:

 $('#setting-box > div').change(function(){ $('span', this).html($('input', this).val()); }); 

确切的替代品是

 $(this).children('span').html($('input', this).val()); 

或尝试(未测试)

 $('> span', this).html($('input', this).val());