仿造 jQuery 的 “$”

如果我们只考虑IE8及以上的浏览器,我们可以通过简单的代码“仿造”出类似jQuery中“$”选择符的效果:

 1 window.$ = function(selector) {
 2   var selectorType = 'querySelectorAll';
 3 
 4   if (selector.indexOf('#') === 0) {
 5       selectorType = 'getElementById';
 6       selector = selector.substr(1, selector.length);
 7   }
 8 
 9   return document[selectorType](selector);
10 };

这段代码之后,你就可以在脚本中使用$来进行大部分选择元素的操作了。

posted @ 2014-12-22 10:54  西山农夫  阅读(208)  评论(0编辑  收藏  举报