jQuery找到$ .find('selector')与$('selector')的区别

r.p*_*ski 16 jquery find css-selectors

我有一个问题,为什么这两个代码片段不同.

$('#ctl00_DDMenu1_HyperLink1')  
//jQuery(a#ctl00_DDMenu1_HyperLink1 Default.aspx) Console output
$('#ctl00_DDMenu1_HyperLink1').text()
Run Code Online (Sandbox Code Playgroud)

上面的代码返回: Some link text

$.find('#ctl00_DDMenu1_HyperLink1')  
//[a#ctl00_DDMenu1_HyperLink1 Default.aspx] Consolee output
$.find('#ctl00_DDMenu1_HyperLink1').text()
Run Code Online (Sandbox Code Playgroud)

返回

TypeError:$.find("#ctl00_DDMenu1_HyperLink1").text不是函数

这是否意味着无法访问$.find返回Array对象[]和jQuery函数?

//编辑

我使用过jQuery 1.4.2并使用过Firebug控制台.

//通过练习找到答案

此代码将返回jQuery对象引用,并且可以访问所有jQuery函数.

$('any_selector')
//jQuery(item1),jQuery(item2),...,jQuery(item-N) Console output $('any_selector').text()

此代码返回JavaScript Array对象,因此jQuery的任何函数都不能应用于resultset.即使结果集似乎相同.

$.find('any_selector')
//[item1,item2,...,item-N] Consolee output
$.find('any_selector').text()

但是我们可以把把js Array包装成jQuery选择器的技巧(奇怪的技巧):

$($.find('any_selector_as_inner_select')).val()

//谢谢你的帮助!

小智 10

这不起作用的原因是因为find()允许您根据已经做出的选择过滤一组元素.例如,如果您想要选择特定表单中的所有输入,您可以编写:

$('#aParticularForm').find('input') 
Run Code Online (Sandbox Code Playgroud)

它不能单独调用.

  • $ .find()函数返回匹配对象的JavaScript数组,因此在纯JS对象中无法访问任何jQuery函数.但是将这些JS对象包装在$()中会影响良好的结果.干杯! (6认同)