How can I detect if a selector returns null?

前端 未结 8 1950
无人及你
无人及你 2020-11-27 09:01

What is the best way to detect if a jQuery-selector returns an empty object. If you do:

alert($(\'#notAnElement\'));

you get [object Object

8条回答
  •  不知归路
    2020-11-27 09:24

    You may want to do this all the time by default. I've been struggling to wrap the jquery function or jquery.fn.init method to do this without error, but you can make a simple change to the jquery source to do this. Included are some surrounding lines you can search for. I recommend searching jquery source for 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 = {
    

    Last but not least, you can get the uncompressed jquery source code here: http://code.jquery.com/

提交回复
热议问题