jQuery assertion support / defensive programming?

前端 未结 4 462
臣服心动
臣服心动 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: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); };
    

提交回复
热议问题