【问题标题】:How can I detect if a selector returns null?如何检测选择器是否返回 null?
【发布时间】:2010-10-29 13:06:51
【问题描述】:

检测 jQuery 选择器是否返回空对象的最佳方法是什么。 如果你这样做:

alert($('#notAnElement'));

你得到了[object Object],所以我现在的做法是:

alert($('#notAnElement').get(0));

这将写入“未定义”,因此您可以对其进行检查。但这似乎非常糟糕。还有什么办法?

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    我最喜欢用这个小小的便利来扩展 jQuery:

    $.fn.exists = function () {
        return this.length !== 0;
    }
    

    像这样使用:

    $("#notAnElement").exists();
    

    比使用长度更明确。

    【讨论】:

    • 你为什么把 'this' 包裹在 $() 中?在这种情况下,'this' 不会实际上指向 jQuery 对象吗?
    • 我发现返回thistrue 更有帮助。请参阅我移植 Rails 的presence 方法的答案。
    • 如果你想保持链接的能力,如果函数返回true,或者你想用这种方法将this分配给一个变量,我建议changing the return statement to what CSharp有。
    • Magnar,你能解释一下这个“扩展”功能是如何工作的吗?我假设它是一个 Javascript 概念,而不是一个严格的 JQuery 概念。我研究了原型设计,但我不确定这是否适用于此以及为什么语法会是“$.fn”。
    • @Adam 是的。但在这种情况下,你应该放弃存在检查,因为 jQuery 是如何工作的。如果没有匹配选择器的元素,它就不会做任何事情。
    【解决方案2】:
    if ( $("#anid").length ) {
      alert("element(s) found")
    } 
    else {
      alert("nothing found")
    }
    

    【讨论】:

      【解决方案3】:

      选择器返回一个 jQuery 对象数组。如果没有找到匹配的元素,则返回一个空数组。您可以查看选择器返回的集合的.length 或查看第一个数组元素是否为'undefined'。

      您可以在 IF 语句中使用 any 以下示例,它们都会产生相同的结果。如果选择器找到匹配的元素,则为 true,否则为 false。

      $('#notAnElement').length > 0
      $('#notAnElement').get(0) !== undefined
      $('#notAnElement')[0] !== undefined
      

      【讨论】:

      • 我使用.length,除非代码很热。这当然是最明确的意图。此外,.size() 已被弃用并且已经存在多年(从 1.8 开始)。我只是要编辑您的答案并将其删除,请随时用注释将其添加回来,但它太旧了,我认为最好不要了。
      • 从技术上讲,它返回一个不包含 DOM 节点的 jQuery 对象。说它返回一个空数组是不对的。
      【解决方案4】:

      我喜欢做这样的事情:

      $.fn.exists = function(){
          return this.length > 0 ? this : false;
      }
      

      那么你可以这样做:

      var firstExistingElement = 
          $('#iDontExist').exists() ||      //<-returns false;
          $('#iExist').exists() ||          //<-gets assigned to the variable 
          $('#iExistAsWell').exists();      //<-never runs
      
      firstExistingElement.doSomething();   //<-executes on #iExist
      

      http://jsfiddle.net/vhbSG/

      【讨论】:

      • @Ehsan 实际上它不是已接受答案的副本...请注意,已接受答案仅返回真/假,而此答案返回 原始对象(“this ") 或错误。如果返回值不为假,则此答案允许您对返回值执行其他操作(例如附加函数链接)。
      • 我的标准工具包中有完全相同的代码。这种形式等同于 Rails 中的 object.presence,在 @CSharp 描述的 fallthrough 结构中非常有用。
      • 这是一个很好的答案,但如果您解释如果不存在任何测试元素会发生什么,将会很有帮助。简短回答:TypeError: firstExistingElement.doSomething is not a function。您可以将整个变量分配/测试包装在 if() 中,并且仅在找到元素时才执行某些操作....
      【解决方案5】:

      我喜欢使用presence,灵感来自Ruby on Rails

      $.fn.presence = function () {
          return this.length !== 0 && this;
      }
      

      你的例子变成了:

      alert($('#notAnElement').presence() || "No object found");
      

      我发现它优于建议的$.fn.exists,因为您仍然可以使用布尔运算符或if,但真实结果更有用。另一个例子:

      $ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
      $ul.append('...')
      

      【讨论】:

        【解决方案6】:

        我的偏好,我不知道为什么 jQuery 中还没有这个:

        $.fn.orElse = function(elseFunction) {
          if (!this.length) {
            elseFunction();
          }
        };
        

        这样使用:

        $('#notAnElement').each(function () {
          alert("Wrong, it is an element")
        }).orElse(function() {
          alert("Yup, it's not an element")
        });
        

        或者,就像它在 CoffeeScript 中的样子:

        $('#notAnElement').each ->
          alert "Wrong, it is an element"; return
        .orElse ->
          alert "Yup, it's not an element"
        

        【讨论】:

          【解决方案7】:

          这在 JQuery 文档中:

          http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

            alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );
          

          【讨论】:

            【解决方案8】:

            默认情况下,您可能希望一直这样做。我一直在努力包装 jquery 函数或 jquery.fn.init 方法来做到这一点而不会出错,但是您可以对 jquery 源进行简单的更改来做到这一点。包括一些您可以搜索的周边线路。我建议在 jquery 源中搜索The jQuery object is actually just the init constructor 'enhanced'

            var
              version = "3.3.1",
            
              // Define a local copy of jQuery
              jQuery = function( selector, context ) {
            
                // The jQuery object is actually just the init constructor 'enhanced'
                // Need init if jQuery is called (just allow error to be thrown if not included)
                var result = new jQuery.fn.init( selector, context );
                if ( result.length === 0 ) {
                  if (window.console && console.warn && context !== 'failsafe') {
                    if (selector != null) {
                      console.warn(
                        new Error('$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:'+context)
                      );
                    }
                  }
                }
                return result;
              },
            
              // Support: Android <=4.0 only
              // Make sure we trim BOM and NBSP
              rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
            
            jQuery.fn = jQuery.prototype = {
            

            最后但同样重要的是,您可以在此处获取未压缩的 jquery 源代码:http://code.jquery.com/

            【讨论】:

              猜你喜欢
              • 2023-03-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-12-14
              • 2020-04-15
              • 2013-02-20
              • 1970-01-01
              相关资源
              最近更新 更多