简体   繁体   English

为什么.find()总是返回true?

[英]Why does .find() always return true?

It seems like jQuery's .find() method always returns true . 似乎jQuery的.find()方法总是返回true But that's not really useful because you have do additionally check the length of the returned object to see if it really exists. 但这并不是很有用,因为你还要检查返回对象的长度,看看它是否真的存在。

Anyone got a good explanation for that behaviour? 有人对这种行为有一个很好的解释吗?

It doesn't return true. 它不会返回true。 It returns an empty set of elements, which is true if you do == . 它返回一组空元素,如果你执行== ,则为true。 You need to check .length and check if 0 elements were returned. 您需要检查.length并检查是否返回了0个元素。

Example how to check if any elements where matched: 示例如何检查匹配的元素是否匹配:

if ( $('body').find('li').length ) {
    // at least one li was found
} else {
   // no li's where found
}

$() and selector methods like find() and filter() always return a jQuery object. $()find()方法(如find()filter()总是返回一个jQuery对象。 This is so you can chain methods. 这样你可以链接方法。 You could do something like 你可以做点什么

$('body').find('li').add('<p>')

This finds all list elements in the body, and adds a paragraph to all. 这将查找正文中的所有列表元素,并向所有人添加一个段落。 If $('body').find('li') would return false because it didn't contain any li's, the add() method would throw an error, because you cannot do false.add() . 如果$('body').find('li')将返回false因为它不包含任何li, add()方法会抛出错误,因为你不能做false.add()

Anyone got a good explanation for that habit ? 有人对这个习惯有一个很好的解释吗?

If .find() were to return a Boolean value instead of a jQuery object, you could not use it for chaining which is one of the overall goals of jQuery. 如果.find()返回一个布尔值而不是jQuery对象,则不能将它用于链接,这是jQuery的总体目标之一。

.find() method of jQuery returns jQuery object , which could be evaluated to true in some cases. jQuery的.find()方法返回jQuery对象 ,在某些情况下可以将其评估为true But in fact comparing it strictly ( === ) with true will fail (the comparison will return false ). 但实际上将它严格( === )与true进行比较将失败(比较将返回false )。

This is why you should use strict comparison ( === instead of == ) and check for .length property when counting returned elements (this is true also about Array objects). 这就是为什么你应该使用严格比较===而不是== )并在计算返回元素时检查.length属性 (对于Array对象也是如此)。

It is completely reasonable, as the jQuery object is only a container for elements you have found. 这是完全合理的,因为jQuery对象只是您找到的元素的容器 It must have jQuery methods (the ones you can call on the result of .find() ), thus it must not be a boolean. 它必须有jQuery方法(你可以在.find()的结果上调用.find() ),因此它不能是布尔值。

Remember 记得

$('selector').find('subselector')

will return the same result set as 将返回相同的结果集

$('subselector', 'selector') or $('selector subselector')

One of the utilities of find() resides in chaining find()的一个实用程序驻留在链接中

$('div table').css('width', '100px')
              .find('tr').css('background-color', 'Red');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM