jQuery assertion support / defensive programming?

前端 未结 4 459
臣服心动
臣服心动 2021-02-07 05:50

Is there any built in support in jQuery for basic assertion checking, primarily of things like \'expected number of returned elements\'.

For instance I may have a simple

相关标签:
4条回答
  • 2021-02-07 06:16

    I created a plugin for that: jquery-assert. You could use it like this:

    Make sure, one or more elements were found, before calling the next function:

    $('#element01').assertFound().val('x')
    

    Assert that 1 element was selected:

    $('#element01').assertOne(); // same as assertFound(1)
    

    Make sure a given number of elements were found before calling further functions:

    $('.item').assertFound(10).find('p').assertFound(10).data(...)
    
    0 讨论(0)
  • 2021-02-07 06:24

    Enhancements to Tomalak’s answer: throw the error to halt execution, include the offending selector and add the assertSingle variant.

    $.fn.assertSize = function(size) {
        if (this.length != size) { 
            throw "Expected " + size + " elements, but selector '" + this.selector + "' found " + this.length + ".";
        }
        return this;
    };
    $.fn.assertSingle = function() { return this.assertSize(1); };
    
    0 讨论(0)
  • 2021-02-07 06:27

    It doesn't look like there is anything built-in. But writing an extension isn't too hard:

    $.fn.assertSize = function(size) { 
      if (this.length != size) { 
        alert("Expected " + size + " elements, but got " + this.length + ".");
        // or whatever, maybe use console.log to be more unobtrusive
      }
      return this;
    };
    

    Usage is exactly as you propose in your question.

    $("#btnSignup").assertSize(1).click(function() {
      return validateForm();
    );
    

    Note that in its current form the function returns successfully even if the assertion fails. Anything you have chained will still be executed. Use return false; instead of return this; to stop further execution of the chain.

    0 讨论(0)
  • 2021-02-07 06:31

    You probably want http://docs.jquery.com/Traversing/eq#index:

    Reduce the set of matched elements to a single element.

    If your selector returns no objects then jQuery simply won't run the chained code as it has no elements to run them on

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