jQuery

jQuery新旧版本共存

1
2
3
4
5
6
7
8
9
10
<script src="jquery-1.5.js"></script>
<script src="jquery-1.11.js"></script>
<script>
// 现在window.$和window.jQuery是1.11版本:
console.log($().jquery); // => '1.11.0'
var $jq = jQuery.noConflict(true);
// 现在window.$和window.jQuery被恢复成1.5版本:
console.log($().jquery); // => '1.5.0'
// 可以通过$jq访问1.11版本的jQuery了
</script>

jQuery中的循环技巧

  • 简单的for-in(事件)

    1
    for ( type in events ) {}
  • 缓存length属性,避免每次都去查找length属性,稍微提升遍历速度。
    但是如果遍历HTMLCollection时,性能提升非常明显,因为每次访问HTMLCollection的属性,HTMLCollection都会内部匹配一次所有的节点

    1
    for ( var j = 0, l = handlers.length; j < l; j++ ) {}
  • 不比较下标,直接判断元素是否为true(强制类型转换)

    1
    2
    3
    4
    5
    var elem;
    for ( var i = 0; elems[i]; i++ ) {
    elem = elems[i];
    // ...
    }

jQuery源码分析笔记

  • js自调用匿名函数的两种写法:
    1
    2
    3
    4
    5
    6
    7
    (function(window, undefined){
    // code
    })(window);

    (function(window, undefined){
    // code
    }(window));
  • undefined能够被重写,赋予新的值。
    1
    2
    undefined = "now it's defined";
    alert( undefined );