Patterns for avoiding jQuery silent fails

前端 未结 3 1336
无人共我
无人共我 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:22

    You could write a plugin:

    jQuery.fn.requireElements = function (amount, exactMatch) {
        if (amount === undefined) {
            amount = 1;
        };
    
        if (this.length < amount || this.length > amount && exactMatch) {
            throw new Error(this.length " elements instead of " (exactMatch ? "at least " : "") + amount);
        };
    
        return this;
    };
    

    Then:

    $('yourSelector').requireElements(2).bind('click', function () {
    
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-02 21:28

    I would recommend using jQuery lint.

    for example

    $(function(){
      var foo = $('.this #is:my(complexSelector)');
    });
    

    will complain both that you have an invalid selector (as given example selector is in fact invalid, though I assume you know that :)), and that no elements where in fact found.

    See http://js.azatoth.net/test/lint.html for an example.

    0 讨论(0)
提交回复
热议问题