2010-05-11 55 views
4

我使用jQuery和我需要得到任何时间和anywere异常(任何操作),如果我附加一些事件或尝试执行某些操作与元素(从选择器)不存在。 在这个问题jQuery中有一些内部的“严格”模式?jQuery异常,如果元素不存在

回答

5

不,没有。

但是,你可以把它简单的插件:

$.fn.checkEmpty = function() { 
    if (!this.length) 
     throw new Error("No elements matched by " + this.selector); 
    return this; 
}; 

$('...').checkEmpty().bind(...); 

或者:

function $s() { return $.apply(this, arguments).checkEmpty(); } 

$s('...').bind(...); 
0

不,这是jQuery的美景。

您可以创建一个包装函数

function myjQuery() { 
    var res = $.apply(this, arguments); 

    if (!res.size()) { 
    throw new Error("No elements matched :("); 
    }; 

    return res; 
}; 

myjQuery('input').each(); 

这不会掩盖使用find()filter()之类返回的空集,但赫姆...

1

检查这个职位的方式来处理“存在”

Exists in jquery

+1

这并不回答问题。 – SLaks 2010-05-11 17:36:32

+0

对,严格模式的真正答案是“否”,没有模式。这只是指出了一些替代方案。 – 2010-05-12 11:49:01