0

我正在编写一个包含很多$(".blahblah").size()>0条件的代码。我想知道是否有一个 JQuery 速记它可以消除键入>1.

这里有一个建议:http: //forum.jquery.com/topic/selector-exists-would-be-a-nice-addition

类似的东西$(...).exists()可以派上用场。有这样的事吗?我在 Internet 上找不到它,我想知道是否有人知道技巧或 JQuery 团队中的任何人知道是否计划添加此类功能?

PS。我读过这个:jQuery 有“存在”功能吗?

4

4 回答 4

3
function moreThanOne(selector){
  return $(selector).length > 1;
}

解决方案是为此使用函数,您也可以使用length而不是size().

来自 Jquery 的文档

.size() 方法在功能上等同于 .length 属性;但是,首选.length 属性,因为它没有函数调用的开销。

于 2012-04-11T07:03:11.157 回答
1

另一种选择是

if($(".blahblah")[0]) { ... }

如果您的目标是减少打字

于 2012-04-11T07:05:13.930 回答
0

您可以像这样创建自己的exists函数:

function exists(selector){
  return jQuery(selector).size() > 0;
}

然后你可以像这样使用它:

if (exists(".blahblah")) {
  // it exists
}

添加到 jQuery 中fn

jQuery.fn.exists = function(){
    return this.length > 0;
}

要使用:

if ($(".blahblah").exists()) {
  // it exists
}

您还可以使用length不需要键入的属性> 0

if ($(".blahblah").length) {
  // it exists
}
于 2012-04-11T07:01:14.607 回答
0

使用“有”选择器。

你可以写:

$(':has(.blahblah:eq(1))') 
于 2012-04-11T07:06:56.230 回答