jQuery 不会告诉你,你正在对空白的选择结果执行一段代码,而且会像一点错都没有那样执行了。 是否要核实选择结果是否为空,完全由你决定的。
// 太遭了,执行了三个方法后才意识到里面是空的
$('#nosuchthing').slideUp();
// 这会好点,就是代码有点长
var $mySelection = $('#nosuchthing');
if ($mySelection.length) { mySelection.slideUp(); }
// 最好的做法是添加一个 doOnce 插件
jQuery.fn.doOnce = function(func){
this.length && func.apply(this);
return this;
}
$('li.cartitems').doOnce(function(){
// make it ajax! \o/
});
这层保护是适用于 jQuery UI widget,因为即使操作的元素为空其开销也不少。
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.