【问题标题】:Jquery shorthand for .size()>1.size()>1 的 Jquery 简写
【发布时间】:2012-04-23 11:38:24
【问题描述】:

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

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

$(...).exists() 之类的东西会很方便。有这样的事吗?我在互联网上找不到它,我想知道是否有人知道技巧或 JQuery 团队的任何人知道是否计划添加此类功能?

PS。我读过这个:Is there an "exists" function for jQuery?

【问题讨论】:

标签: jquery


【解决方案1】:
function moreThanOne(selector){
  return $(selector).length > 1;
}

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

来自 Jquery 的文档

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

【讨论】:

    【解决方案2】:

    另一种选择是

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

    如果您的目标是减少打字次数

    【讨论】:

      【解决方案3】:

      您可以像这样创建自己的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
      }
      

      您也可以使用不需要输入> 0length 属性:

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

      【讨论】:

      • 谢谢,但由于可读性,我会选择 jQuery.fn.exists = function(){return this.length>0;} 解决方案。
      • @AlexStack:是的,这更好,我已经更新了答案:)顺便说一句,你也可以简单地做if ($(".blahblah").length),而无需输入> 0
      • 是的,这是一个很好的建议,但是为了代码的可读性,我更喜欢 >0 我寻找 exist() 函数的原因首先是可读性而不是速度。
      【解决方案4】:

      使用“有”选择器。

      你可以写:

      $(':has(.blahblah:eq(1))') 
      

      【讨论】:

        猜你喜欢
        • 2013-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 2011-08-31
        • 2014-12-17
        相关资源
        最近更新 更多