.length
是你的朋友调试jQuery的时候。因为即使:
document.getElementById('nonexistent');
将在JavaScript中返回null
,使用jQuery选择将返回一个对象,并投true
:
if(!document.getElementById('nonexistent')) {
alert('not here!');
}
if(!$('#nonexistent')) {
alert('here, here!');
}
这意味着:
$('#nonexistent').doSomething().doSomethingElse().whatever();
可能会不是扔错误,所以你会很难知道什么“没有工作”在茶在。
然而,检查对象长篇作品:
if(!$('#nonexistent').length) {
alert('not here!');
}
jQuery是旨在默默地消失,因为它的一个核心使用情况的链接。如果选择器或原型方法在链中返回null或false,使用jQuery会比大多数没有经验的程序员想要的更频繁地抛出空引用错误。
更新
则很可能通过,如果在调试模式下修改原型做自己的调试。我尝试这样做:
var debug = ['hide','show'], // Array of jQuery methods to debug
i = 0, name;
for(; debug[i]; i++) {
name = debug[i];
if (typeof $.fn[name] == 'function') {
$.fn[name] = (function(name, fn) {
return function() {
if (!this.length) {
console.warn('No elements selected when calling '+name);
}
fn.apply(this, Array.prototype.slice.call(arguments));
};
}(name, $.fn[name]));
}
}
现在,每当我称之为“隐藏”,它会提醒我,如果有在链中没有任何元素:
$('#nonexistent').hide(); // consoles a warning
小提琴:http://jsfiddle.net/B4XQx/
你能给出一个例? – JohnFx
任何示例代码? –
我从来没有尝试过使用它,但是你看过['error()'](http://api.jquery.com/error/)?不过,这是否会抓住潜在的JavaScript错误,我不确定。 –