Patterns for avoiding jQuery silent fails

前端 未结 3 1357
无人共我
无人共我 2021-01-02 20:45

Is there any good practice to avoid your jQuery code silently fail?

For example:

$(\'.this #is:my(complexSelector)\').doSomething();
3条回答
  •  渐次进展
    2021-01-02 21:28

    It's not necessarily wrong when a selector matches nothing; it depends on your application. You could write your own validateNonEmpty plugin:

    jQuery.fn.validateNonEmpty = function() {
      if (this.length == 0)
        throw "Empty list detected - selector: " + this.selector;
      return this; // thanks @Matt
    };
    

    Then you can do:

    $('something something').validateNonEmpty().doSomething();
    

    Also, note that you want to check to see if the length is 0, not less than 0.

提交回复
热议问题