[英]jQuery exception if element doesn't exist
我使用jQuery并且我需要获得任何时间和任何异常(使用任何操作),如果我附加一些事件或尝试使用不存在的元素(从选择器获取)执行某些操作。 这个问题在jQuery中是否有一些内部的“严格”模式?
不,没有。
但是,你可以为它制作一个简单的插件:
$.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(...);
查看这篇文章,了解处理“存在”的方法
不,这是jQuery的魅力所在。
您可以创建一个包装函数
function myjQuery() {
var res = $.apply(this, arguments);
if (!res.size()) {
throw new Error("No elements matched :(");
};
return res;
};
myjQuery('input').each();
这不会掩盖使用find()
或filter()
等返回的空集,但是humm ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.