24

如果 $('#id') 不匹配任何内容会返回什么?我认为它会是 null 或 false 或类似的东西,所以我尝试像这样检查:

var item = $('#item');
if (!item){
    ...
}

但这没有用。

4

4 回答 4

51

您可以使用以下方法找到匹配的元素数量:

$('selector').length

要检查是否没有匹配的元素,请使用:

var item = $('#item');
if (item.length == 0) {
  // ...
}
于 2009-05-24T17:07:35.133 回答
7

While $('selector').length is great for finding out how many objects your selector matches, its actually completely unnecesary. The thing about jQuery is that all selector based functions use length internally, so you could just do $(selector).hide() (or whatever) and it takes no action for an empty set.

于 2009-05-24T18:01:52.527 回答
5

一个不包含 DOM 节点的 jQuery 对象。

你应该可以使用

var item = $('#item');
if (!item[0]){
    ...
}

为您的存在检查。

于 2009-05-24T17:04:02.593 回答
1

长度属性的别名是 size() 方法。所以你基本上也可以查询:

$("选择器").size()

查看匹配的元素数量。

于 2009-05-24T17:41:28.020 回答