我只花了几个小时来完成以下场景:(全部回到基础)
$('#typo').bind('click' etc ...
我在选择器中输入了一个拼写错误,但是jQuery解析了
$('#funny something out there').bind(...
没有任何警告。
当选择器什么都没有时,是否可以告诉jQuery引发错误?
这样的事情:
$('#typo', alert('Stupid, nothing here! like '+ '#typo))
修改
我对我说:
$('#typo', alert('Stupid, nothing here! like '+ '#typo))
不是一个解决方案。我必须知道错误在哪里扩展选择器
答案 0 :(得分:12)
您可以使用以下代码段:
更新以照顾上下文
jQuery.debug = true;
$ = function (selector, context) {
if (jQuery.debug && typeof selector === "string" && !jQuery(selector, context).length)
throw new Error("No element found!");
return jQuery.apply(this, arguments);
};
答案 1 :(得分:2)
var element = $('#typo');
if (element.length > 0) {
// element exists
}
除此之外,您必须修改jQuery源代码才能获得该行为。
答案 2 :(得分:0)
jquery选择器返回一个DOM元素数组,所以如果你检查它的长度,如果它大于0就会找到一些东西,如果它等于0则它没有
if($("selector").length > 0) found;
答案 3 :(得分:0)
您可以将返回的DOM元素的长度用作falsy并像这样抛出一个新的error
:
var el = '#el';
if ($(el).length){
// Do Stuff
} else {
throw new Error("Element "+el+" Doesn't Exist");
}
或强>
// Ignores Empty Selector
if ($('#el').length){
// Do Stuff
}
我希望这有帮助!