以下内容来自于《众妙之门:JavaScript 与 jQuery 技术精粹》一书,为本人在阅读的时候感觉有必要记录的地方记录而来。
var d; if(x < 200){ d = 1; } else { d = -1; } var d = x < 200 ? 1 : -1; |
---|
/* cached outside loop*/ var len = myArray.length; for (var i = 0; i < len; i++) {} /* cached inside loop */ /* 数组长度在每个循环中都被不必要的重复访问,如此导致程序运行缓慢*/ for (var i = 0, len = myArray.length; i < len; i++){} /* cached outside loop using while */ var len = myArray.length; while (len--){} |
---|
问题:程序中使用的命名空间是正确的,但对其存在性的检查无效。如下例:
if (!MyNamespace){ MyNamespace = {}; } |
---|
执行过程中!MyNamespace 会报错,变量之前么有做声明。较好的处理方式:
方式一
if (!MyNamespace){ MyNamespace = {}; } |
---|
方式二
var MyNamespace = MyNamespace || {}; |
---|
方式三
if( typeof MyNamespace == 'undefined'){ var MyNamespace = {}; } |
---|
typeof null > "object" //Null 是一个对象 null instanceof Object > false //Null 不是对象的实例 typeof NaN > "number" //NaN 是一个数字 NaN === NaN > false //NaN 不等于任何值 new Array() == false > true //空数组 == false |
---|
根源:特定于浏览器的代码
parent()
用于匹配元素的直接父元素。
parents()
类似于parent()
,返回的是多个父元素。
closest()
类似于parents()
,但只返回一个父元素或祖先元素,且为最近的元素。
position()
计算相对于偏移父元素(即含有position:relative 的元素的最近父元素,如果没有,相对于文档)
offset()
则总是计算相对于文档的位置。
前者返回字符型维度,以px 为单位;后者返回整数型维度。
bind()
可以一次绑定多个事件,并可以传递回调函数。
var message = "right"; $("a").bind("click contextmenu", { msg: message }, function(e) { alert(e.data.msg); return false; }); |
---|
live()
类似bind()
,区别在于可将事件绑定到当前和将来的元素(通过DOM 脚本生成的元素)
delegate()
在jQuery 1.4.2 中出现的未来弥补live()
无法直接用于链式结构。
//无效的 $("#test").children("a").live("mouseover", function() { alert("hello"); }); // $("#test").delegate("a", "mouseover", function() { alert("hello"); }); |
---|
not()
返回不匹配的元素、is()
只会返回布尔值、:not()
可用于选择器字符串中。