JQuery:如何在$(this)中找到名为“apples”的输入?

时间:2021-11-21 02:29:26

I'm learning JQuery and have found the factory function $() with its selectors quite useful. However, I cannot figure out how to select within a particular element I have named as a variable. For example:

我正在学习JQuery并且发现工厂函数$()及其选择器非常有用。但是,我无法弄清楚如何在我已命名为变量的特定元素中进行选择。例如:

var thisDiv = $("#myDiv");

// thisDiv looks like this:
<div id="myDiv">
<input id="apples" />
<input id="bananas" />
</div>

How would I select the input with id="apples" given only the variable thisDiv in JQuery? Thanks!

如果只给出JQuery中的变量thisDiv,我将如何选择id =“apples”的输入?谢谢!

5 个解决方案

#1


$("#thisDiv #apples")

But you can also do:

但你也可以这样做:

thisDiv.find("#apples"); // use find method

and also:

$("#apples", thisDiv); // provide context

#2


You could try this

你可以试试这个

thisDiv.find('#apples');

#3


You should be able to select it by searching within your div like:

您应该可以通过在div中搜索来选择它:

 $("#myDiv").find("#apples")

#4


$('#apples', thisDiv);

#5


Perhaps yours was only an example and not representative of the proper code, but it's worth mentioning that an ID is unique per document, therefore you don't particularly need the context.

也许你的只是一个例子,并不代表正确的代码,但值得一提的是每个文档的ID都是唯一的,因此你并不特别需要上下文。

$('#apples');
$('#apples', thisDiv);  // same result, more lookups

If it was just an example, and you wanted to know how to find any element, using any selector, then yep, the other answers here are all correct.

如果它只是一个例子,你想知道如何找到任何元素,使用任何选择器,那么,这里的其他答案都是正确的。

thisDiv.find('li.myClass'); // or,
$('li.myClass', thisDiv);

#1


$("#thisDiv #apples")

But you can also do:

但你也可以这样做:

thisDiv.find("#apples"); // use find method

and also:

$("#apples", thisDiv); // provide context

#2


You could try this

你可以试试这个

thisDiv.find('#apples');

#3


You should be able to select it by searching within your div like:

您应该可以通过在div中搜索来选择它:

 $("#myDiv").find("#apples")

#4


$('#apples', thisDiv);

#5


Perhaps yours was only an example and not representative of the proper code, but it's worth mentioning that an ID is unique per document, therefore you don't particularly need the context.

也许你的只是一个例子,并不代表正确的代码,但值得一提的是每个文档的ID都是唯一的,因此你并不特别需要上下文。

$('#apples');
$('#apples', thisDiv);  // same result, more lookups

If it was just an example, and you wanted to know how to find any element, using any selector, then yep, the other answers here are all correct.

如果它只是一个例子,你想知道如何找到任何元素,使用任何选择器,那么,这里的其他答案都是正确的。

thisDiv.find('li.myClass'); // or,
$('li.myClass', thisDiv);