是否可以使用“>"选择“此"对象的子对象? [英] Is it possible to use '>' to select a child of 'this' object?

查看:102
本文介绍了是否可以使用“>"选择“此"对象的子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The original problem I face is like this:

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

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

I have done some research and found this post: How to get the children of the $(this) selector?

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

The two parameters way actually works for me

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

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

And now my question is, is there any method to select this span element,

在$()中使用单个参数? (并且不使用find(),child()等方法)

using single parameter in the $()? (and not using method like find(), child(), etc)

就像,有什么事情/方法可以做$(this > childElement)吗?

Like, is there any thing / way to do $(this > childElement) ?

感谢您的帮助

推荐答案

要直接回答您的问题,没有单一的参数方法可以只搜索jQuery中this元素的子级.这是因为jQuery的默认上下文是整个文档,因此要进行更改,除了选择器之外,您还必须使用一些其他代码.

To answer your question directly, there is no single argument way to just search children of the this element in jQuery. That's because the default context for jQuery is the entire document so to change that, you HAVE to use some additional code besides just the selector.

此外,DOM元素本身(在示例中为this变量)无法进入选择器,因为选择器是字符串,而DOM元素没有任何方法可以在选择器字符串中表达它.因此,您必须使用一个额外的参数来将选择器的搜索范围限定为小于文档的范围.

Further, a DOM element itself (in the this variable in your example) can't go into a selector because the selector is a string and a DOM element doesn't have any way to express it in a selector string. So, you have to use an extra argument to qualify what scope is searched for the selector to something smaller than just the document.

因此,为了限制选择器搜索的范围,您可以使用听起来似乎已经了解的选项:

So, to restrict the scope of the selector search, that leaves you with the options that it sounds like you may already know about:

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

如果我想要任何后代,我自己更喜欢使用.find(),因为我认为代码更容易阅读.因此,为满足您的特定需求,我将使用此代码:

If I want any descendant, I myself prefer to use .find() because I think the code is more directly readable. So, for your particular need, I'd use this:

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

或者,如果仅是直子:

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


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


In addition, your .change() code should be bound to an element that actually supports that event which would be something like a <select> or <input>, not a regular <div>.

这篇关于是否可以使用“&gt;"选择“此"对象的子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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