你可能不需要jQuery!使用原生JavaScript 進行開發

lhb25發表於2014-02-23

  很多的 JavaScript 開發人員,包括我在內,都很喜歡 jQuery。因為它的簡單,因為它有很多豐富的外掛可供使用,和其它優秀的工具一樣,jQuery 讓我們開發人員能夠更輕鬆的開發網站和 Web 應用。

  然而,另一方面,作為前端開發的基礎框架,jQuery 包含大量的相容性程式碼和擴充套件功能,其中有很多在你的整個專案中可能都不會用到。其實如果你只是針對現代瀏覽器,很多功能使用原生的 JavaScript 就可以實現,即使是拖後腿的低版本 IE 瀏覽器,相容性也是很容易處理的。

  下面就帶大家一起看看在 IE 瀏覽器環境中如果使用原生 JavaScript 程式碼實現 jQuery 中的功能。如果你打算自己開發一個小的基礎框架,可以好好參考一下這些程式碼的實現。

  Ajax Post

jQuery:

$.ajax({
  type: 'POST',
  url: '/my/url',
  data: data
});

IE8+:

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.send(data);

  Ajax Get

jQuery:

$.ajax({
  type: 'GET',
  url: '/my/url',
  success: function(resp) {

  },
  error: function() {

  }
}); 

  IE8+:

request = new XMLHttpRequest();
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:

$.getJSON('/my/url', function(data) {

});

  IE8+:

request = new XMLHttpRequest();
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:

$(el).fadeIn();  

  IE8+:

function fadeIn(el) {
  var opacity = 0;

  el.style.opacity = 0;
  el.style.filter = '';

  var last = +new Date();
  var tick = function() {
    opacity += (new Date() - last) / 400;
    el.style.opacity = opacity;
    el.style.filter = 'alpha(opacity=' + (100 * opacity)|0 + ')';

    last = +new Date();

    if (opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
  };

  tick();
}

fadeIn(el);

  顯示和隱藏

  jQuery:

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

  IE8+:

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

  新增 Class

  jQuery:

$(el).addClass(className);

  IE8+:

if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

  插入 HTML

  jQuery:

$(el).before(htmlString);
$(parent).append(el);
$(el).after(htmlString);

  IE8+:

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

  獲取子節點

  jQuery:

$(el).children();

  IE8+:

var children = [];
for (var i=el.children.length; i--;){
  // Skip comment nodes on IE8
  if (el.children[i].nodeType != 8)
    children.unshift(el.children[i]);
}

  迴圈節點

  jQuery:

$(selector).each(function(i, el){

});

  IE8+:

function forEachElement(selector, fn) {
  var elements = document.querySelectorAll(selector);
  for (var i = 0; i < elements.length; i++)
    fn(elements[i], i);
}

forEachElement(selector, function(el, i){

});

  清空節點

  jQuery:

$(el).empty();

  IE8+:

while(el.firstChild)
  el.removeChild(el.firstChild)

  過濾節點

  jQuery:

$(selector).filter(filterFn);

  IE8+:

function filter(selector, filterFn) {
  var elements = document.querySelectorAll(selector);
  var out = [];
  for (var i = elements.length; i--;) {
    if (filterFn(elements[i]))
      out.unshift(elements[i]);
  }
  return out;
}

filter(selector, filterFn);

  查詢元素

  jQuery:

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

  IE8+:

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

  獲取屬性、HTML或者文字

  jQuery:

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

  IE8+:

el.getAttribute('tabindex');
el.innerHTML
el.outerHTML
el.textContent || el.innerText

  判斷是否包含某個 css class

  jQuery:

$(el).hasClass(className);

  IE8+:

if (el.classList)
  el.classList.contains(className);
else
  new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className); 

  選擇器匹配

  jQuery:

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

  IE8+:

var matches = 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 {
    var nodes = el.parentNode.querySelectorAll(selector);
    for (var i = nodes.length; i--;)
      if (nodes[i] === el) {
        return true;
    }
    return false;
}

matches(el, '.my-class');

  前一個節點

  jQuery:

$(el).prev();

  IE8+:

// prevSibling can include text nodes
function previousElementSibling(el) {
  do { el = el.previousSibling; } while ( el && el.nodeType !== 1 );
  return el;
}

el.previousElementSibling || previousElementSibling(el);

  後一個節點

  jQuery:

$(el).next();

  IE8+:

// nextSibling can include text nodes
function nextElementSibling(el) {
  do { el = el.nextSibling; } while ( el && el.nodeType !== 1 );
  return el;
}

el.nextElementSibling || nextElementSibling(el);

  外部高度

  jQuery:

$(el).outerHeight()

  IE8+:

function outerHeight(el, includeMargin){
  var height = el.offsetHeight;

  if(includeMargin){
    var style = el.currentStyle || getComputedStyle(el);
    height += parseInt(style.marginTop) + parseInt(style.marginBottom);
  } 
  return height;
}

outerHeight(el, true);

  外部寬度

  jQuery:

$(el).outerWidth()

IE8+:

function outerWidth(el, includeMargin){
  var height = el.offsetWidth;

  if(includeMargin){
    var style = el.currentStyle || getComputedStyle(el);
    height += parseInt(style.marginLeft) + parseInt(style.marginRight);
  } 
  return height;
}

outerWidth(el, true);

  判斷是否陣列

jQuery:

$.isArray(arr);

  IE8+:

isArray = Array.isArray || function(arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
}

isArray(arr);

  陣列轉換

  jQuery:

$.map(array, function(value, index){

})

  IE8+:

function map(arr, fn) {
  var results = []
  for (var i = 0; i < arr.length; i++)
    results.push(fn(arr[i], i))
  return results
}

map(array, function(value, index){

})

  類似的還有很多很多,可以參考這裡:http://youmightnotneedjquery.com/

相關文章