jQuery部分方法对应的原生JS代码

来源:互联网 发布:hbase java 条件查询 编辑:程序博客网 时间:2024/05/29 09:01

原文地址:http://www.admin10000.com/document/3929.html

很多的 JavaScript 开发人员,包括我在内,都很喜欢 jQuery。因为它的简单,因为它有很多丰富的插件可供使用,和其它优秀的工具一样,jQuery 让我们开发人员能够更轻松的开发网站和 Web 应用。

  然而,另一方面,作为前端开发的基础框架,jQuery 包含大量的兼容性代码和扩展功能,其中有很多在你的整个项目中可能都不会用到。其实如果你只是针对现代浏览器,很多功能使用原生的 JavaScript 就可以实现,即使是拖后腿的低版本 IE 浏览器,兼容性也是很容易处理的。

  下面就带大家一起看看在 IE 浏览器环境中如果使用原生 JavaScript 代码实现 jQuery 中的功能。如果你打算自己开发一个小的基础框架,可以好好参考一下这些代码的实现。

  Ajax Post

jQuery:

1
2
3
4
5
$.ajax({
  type:'POST',
  url:'/my/url',
  data: data
});

IE8+:

1
2
3
varrequest = newXMLHttpRequest();
request.open('POST','/my/url',true);
request.send(data);

  Ajax Get

jQuery:

1
2
3
4
5
6
7
8
9
10
$.ajax({
  type:'GET',
  url:'/my/url',
  success:function(resp) {
 
  },
  error:function() {
 
  }
}); 

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
request = newXMLHttpRequest();
request.open('GET','/my/url',true);
 
request.onreadystatechange = function() {
  if(this.readyState === 4){
    if(this.status >= 200 && this.status < 400){
      // Success!
      resp = this.responseText;
    }else{
      // Error :(
    }
  }
}
 
request.send();
request = null;

  加载 JSON

  jQuery:

1
2
3
$.getJSON('/my/url',function(data) {
 
});

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
request = newXMLHttpRequest();
request.open('GET','/my/url',true);
 
request.onreadystatechange = function() {
  if(this.readyState === 4){
    if(this.status >= 200 && this.status < 400){
      // Success!
      data = JSON.parse(this.responseText);
    }else{
      // Error :(
    }
  }
}
 
request.send();
request = null;

  淡入效果

  jQuery:

1
$(el).fadeIn();  

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
functionfadeIn(el) {
  varopacity = 0;
 
  el.style.opacity = 0;
  el.style.filter = '';
 
  varlast = +newDate();
  vartick = function() {
    opacity += (newDate() - last) / 400;
    el.style.opacity = opacity;
    el.style.filter = 'alpha(opacity='+ (100 * opacity)|0 + ')';
 
    last = +newDate();
 
    if(opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
  };
 
  tick();
}
 
fadeIn(el);

  显示和隐藏

  jQuery:

1
2
$(el).show();
$(el).hide();

  IE8+:

1
2
el.style.display = '';
el.style.display = 'none';

  添加 Class

  jQuery:

1
$(el).addClass(className);

  IE8+:

1
2
3
4
if(el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

  插入 HTML

  jQuery:

1
2
3
$(el).before(htmlString);
$(parent).append(el);
$(el).after(htmlString);

  IE8+:

1
2
3
el.insertAdjacentHTML('beforebegin', htmlString);
parent.appendChild(el);
el.insertAdjacentHTML('afterend', htmlString);

  获取子节点

  jQuery:

1
$(el).children();

  IE8+:

1
2
3
4
5
6
varchildren = [];
for(vari=el.children.length; i--;){
  // Skip comment nodes on IE8
  if(el.children[i].nodeType != 8)
    children.unshift(el.children[i]);
}

  循环节点

  jQuery:

1
2
3
$(selector).each(function(i, el){
 
});

  IE8+:

1
2
3
4
5
6
7
8
9
functionforEachElement(selector, fn) {
  varelements = document.querySelectorAll(selector);
  for(vari = 0; i < elements.length; i++)
    fn(elements[i], i);
}
 
forEachElement(selector,function(el, i){
 
});

  清空节点

  jQuery:

1
$(el).empty();

  IE8+:

1
2
while(el.firstChild)
  el.removeChild(el.firstChild)

  过滤节点

  jQuery:

1
$(selector).filter(filterFn);

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
functionfilter(selector, filterFn) {
  varelements = document.querySelectorAll(selector);
  varout = [];
  for(vari = elements.length; i--;) {
    if(filterFn(elements[i]))
      out.unshift(elements[i]);
  }
  returnout;
}
 
filter(selector, filterFn);

  查找元素

  jQuery:

1
2
$(el).find(selector);
$('.my #awesome selector');

  IE8+:

1
2
el.querySelectorAll(selector);
document.querySelectorAll('.my #awesome selector');

  获取属性、HTML或者文本

  jQuery:

1
2
3
4
$(el).attr('tabindex');
$(el).html();
$('<div>').append($(el).clone()).html();
$(el).text();

  IE8+:

1
2
3
4
el.getAttribute('tabindex');
el.innerHTML
el.outerHTML
el.textContent || el.innerText

  判断是否包含某个 css class

  jQuery:

1
$(el).hasClass(className);

  IE8+:

1
2
3
4
if(el.classList)
  el.classList.contains(className);
else
  newRegExp('(^| )' + className + '( |$)','gi').test(el.className); 

  选择器匹配

  jQuery:

1
$(el).is('.my-class');

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
varmatches = function(el, selector) {
  var_matches = (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector);
 
  if(_matches) {
    return_matches.call(el, selector);
  }else{
    varnodes = el.parentNode.querySelectorAll(selector);
    for(vari = nodes.length; i--;)
      if(nodes[i] === el) {
        returntrue;
    }
    returnfalse;
}
 
matches(el,'.my-class');

  前一个节点

  jQuery:

1
$(el).prev();

  IE8+:

1
2
3
4
5
6
7
// prevSibling can include text nodes
functionpreviousElementSibling(el) {
  do{ el = el.previousSibling; } while( el && el.nodeType !== 1 );
  returnel;
}
 
el.previousElementSibling || previousElementSibling(el);

  后一个节点

  jQuery:

1
$(el).next();

  IE8+:

1
2
3
4
5
6
7
// nextSibling can include text nodes
functionnextElementSibling(el) {
  do{ el = el.nextSibling; } while( el && el.nodeType !== 1 );
  returnel;
}
 
el.nextElementSibling || nextElementSibling(el);

  外部高度

  jQuery:

1
$(el).outerHeight()

  IE8+:

1
2
3
4
5
6
7
8
9
10
11
functionouterHeight(el, includeMargin){
  varheight = el.offsetHeight;
 
  if(includeMargin){
    varstyle = el.currentStyle || getComputedStyle(el);
    height += parseInt(style.marginTop) + parseInt(style.marginBottom);
  }
  returnheight;
}
 
outerHeight(el,true);

  外部宽度

  jQuery:

1
$(el).outerWidth()

IE8+:

1
2
3
4
5
6
7
8
9
10
11
functionouterWidth(el, includeMargin){
  varheight = el.offsetWidth;
 
  if(includeMargin){
    varstyle = el.currentStyle || getComputedStyle(el);
    height += parseInt(style.marginLeft) + parseInt(style.marginRight);
  }
  returnheight;
}
 
outerWidth(el,true);

  判断是否数组

jQuery:

1
$.isArray(arr);

  IE8+:

1
2
3
4
5
isArray = Array.isArray || function(arr) {
  returnObject.prototype.toString.call(arr) == '[object Array]';
}
 
isArray(arr);

  数组转换

  jQuery:

1
2
3
$.map(array,function(value, index){
 
})

  IE8+:

1
2
3
4
5
6
7
8
9
10
functionmap(arr, fn) {
  varresults = []
  for(vari = 0; i < arr.length; i++)
    results.push(fn(arr[i], i))
  returnresults
}
 
map(array,function(value, index){
 
})
0 0