你可能不需要jQuery-jQuery的兼容写法大全

发布于 2017-07-18 10:54:15 字数 17052 浏览 1841 评论 0

你可能不需要jQuery,这是一个网站的标题和域名,这个网站主要告诉你在不使用jQuery的情况下,我们改如何编写代码,每个浏览器都能处理一些操作。

简介

jQuery可以说是最棒的前端开发库,几乎在任何一个网站上都能看到他的身影,而且如果开发应用程序更容易的话,可以使用它们,更快的开发出优秀的应用。

另一方面,如果你正在开发一个应用,请认真的考虑下,你是否真的很需要jQuery这个查看,可能你只是包含几行实用代码,后面就不需要jQuery了,如果你只是需要兼容现在主流的浏览器,你可能不需要任何比浏览器附带的更多的东西。

至少,要确保你知道jQuery在为你做什么,以及它不是什么。一些开发商认为,jQuery能有效的解决多个浏览器兼容问题,事实上,每个浏览器是很容易处理自己的一些方法。

AJAX

JSON

jQuery

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

IE9+

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

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Post

jQuery

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

IE8+

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

Request

jQuery

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

  },
  error: function() {

  }
});

IE9+

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

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Effects

Fade In

jQuery

$(el).fadeIn();

IE9+

function fadeIn(el) {
  el.style.opacity = 0;

  var last = +new Date();
  var tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / 400;
    last = +new Date();

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

  tick();
}

fadeIn(el);

Hide

jQuery

$(el).hide();

IE8+

el.style.display = 'none';

Show

jQuery

$(el).show();

IE8+

el.style.display = '';

Elements

Add Class

jQuery

$(el).addClass(className);

IE8+

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

After

jQuery

$(el).after(htmlString);

IE8+

el.insertAdjacentHTML('afterend', htmlString);

Append

jQuery

$(parent).append(el);

IE8+

parent.appendChild(el);

Before

jQuery

$(el).before(htmlString);

IE8+

el.insertAdjacentHTML('beforebegin', htmlString);

Children

jQuery

$(el).children();

IE9+

el.children

Clone

jQuery

$(el).clone();

IE8+

el.cloneNode(true);

Contains

jQuery

$.contains(el, child);

IE8+

el !== child && el.contains(child);

Contains Selector

jQuery

$(el).find(selector).length;

IE8+

el.querySelector(selector) !== null

Each

jQuery

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

IE9+

var elements = document.querySelectorAll(selector);
Array.prototype.forEach.call(elements, function(el, i){});

Empty

jQuery

$(el).empty();

IE9+

el.innerHTML = '';

Filter

jQuery

$(selector).filter(filterFn);

IE9+

Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);

Find Children

jQuery

$(el).find(selector);

IE8+

el.querySelectorAll(selector);

Find Elements

jQuery

$('.my #awesome selector');

IE8+

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

Get Attributes

jQuery

$(el).attr('tabindex');

IE8+

el.getAttribute('tabindex');

Get Html

jQuery

$(el).html();

IE8+

el.innerHTML

Get Outer Html

jQuery

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

IE8+

el.outerHTML

Get Style

jQuery

$(el).css(ruleName);

IE9+

getComputedStyle(el)[ruleName];

Get Text

jQuery

$(el).text();

IE9+

el.textContent

Has Class

jQuery

$(el).hasClass(className);

IE8+

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

Matches

jQuery

$(el).is($(otherEl));

IE8+

el === otherEl

Matches Selector

jQuery

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

IE9+

var matches = function(el, selector) {
  return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
};

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

Next

jQuery

$(el).next();

IE9+

el.nextElementSibling

Offset

jQuery

$(el).offset();

IE8+

var rect = el.getBoundingClientRect();
{
  top: rect.top + document.body.scrollTop,
  left: rect.left + document.body.scrollLeft
}

Offset Parent

jQuery

$(el).offsetParent();

IE8+

el.offsetParent || el

Outer Height

jQuery

$(el).outerHeight();

IE8+

el.offsetHeight

Outer Height With Margin

jQuery

$(el).outerHeight(true);

IE9+

function outerHeight(el) {
  var height = el.offsetHeight;
  var style = getComputedStyle(el);

  height += parseInt(style.marginTop) + parseInt(style.marginBottom);
  return height;
}

outerHeight(el);

Outer Width

jQuery

$(el).outerWidth();

IE8+

el.offsetWidth

Outer Width With Margin

jQuery

$(el).outerWidth(true);

IE9+

function outerWidth(el) {
  var width = el.offsetWidth;
  var style = getComputedStyle(el);

  width += parseInt(style.marginLeft) + parseInt(style.marginRight);
  return width;
}

outerWidth(el);

Parent

jQuery

$(el).parent();

IE8+

el.parentNode

Position

jQuery

$(el).position();

IE8+

{left: el.offsetLeft, top: el.offsetTop}

Position Relative To Viewport

jQuery

var offset = el.offset();

{
  top: offset.top - document.body.scrollTop,
  left: offset.left - document.body.scrollLeft
}

IE8+

el.getBoundingClientRect()

Prepend

jQuery

$(parent).prepend(el);

IE8+

parent.insertBefore(el, parent.firstChild);

Prev

jQuery

$(el).prev();

IE9+

el.previousElementSibling

Remove

jQuery

$(el).remove();

IE8+

el.parentNode.removeChild(el);

Remove Class

jQuery

$(el).removeClass(className);

IE8+

if (el.classList)
  el.classList.remove(className);
else
  el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');

Replace From Html

jQuery

$(el).replaceWith(string);

IE8+

el.outerHTML = string;

Set Attributes

jQuery

$(el).attr('tabindex', 3);

IE8+

el.setAttribute('tabindex', 3);

Set Html

jQuery

$(el).html(string);

IE8+

el.innerHTML = string;

Set Style

jQuery

$(el).css('border-width', '20px');

IE8+

// Use a class if possible
el.style.borderWidth = '20px';

Set Text

jQuery

$(el).text(string);

IE9+

el.textContent = string;

Siblings

jQuery

$(el).siblings();

IE9+

Array.prototype.filter.call(el.parentNode.children, function(child){
  return child !== el;
});

Toggle Class

jQuery

$(el).toggleClass(className);

IE9+

if (el.classList) {
  el.classList.toggle(className);
} else {
  var classes = el.className.split(' ');
  var existingIndex = classes.indexOf(className);

  if (existingIndex >= 0)
    classes.splice(existingIndex, 1);
  else
    classes.push(className);

  el.className = classes.join(' ');
}

Events

Off

jQuery

$(el).off(eventName, eventHandler);

IE9+

el.removeEventListener(eventName, eventHandler);

On

jQuery

$(el).on(eventName, eventHandler);

IE9+

el.addEventListener(eventName, eventHandler);

Ready

jQuery

$(document).ready(function(){});

IE9+

function ready(fn) {
  if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

Trigger Custom

jQuery

$(el).trigger('my-event', {some: 'data'});

IE9+

if (window.CustomEvent) {
  var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('my-event', true, true, {some: 'data'});
}

el.dispatchEvent(event);

Trigger Native

jQuery

$(el).trigger('change');

IE9+

// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);

Utils

Bind

jQuery

$.proxy(fn, context);

IE9+

fn.bind(context);

Array Each

jQuery

$.each(array, function(i, item){});

IE9+

array.forEach(function(item, i){});

Deep Extend

jQuery

$.extend(true, {}, objA, objB);

IE8+

var deepExtend = function(out) {
  out = out || {};

  for (var i = 1; i < arguments.length; i++) {
    var obj = arguments[i];

    if (!obj)
      continue;

    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (typeof obj[key] === 'object')
          out[key] = deepExtend(out[key], obj[key]);
        else
          out[key] = obj[key];
      }
    }
  }

  return out;
};

deepExtend({}, objA, objB);

Extend

jQuery

$.extend({}, objA, objB);

IE8+

var extend = function(out) {
  out = out || {};

  for (var i = 1; i < arguments.length; i++) {
    if (!arguments[i])
      continue;

    for (var key in arguments[i]) {
      if (arguments[i].hasOwnProperty(key))
        out[key] = arguments[i][key];
    }
  }

  return out;
};

extend({}, objA, objB);

Index Of

jQuery

$.inArray(item, array);

IE9+

array.indexOf(item);

Is Array

jQuery

$.isArray(arr);

IE9+

Array.isArray(arr);

Map

jQuery

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

IE9+

array.map(function(value, index){});

Now

jQuery

$.now();

IE9+

Date.now();

Parse Html

jQuery

$.parseHTML(htmlString);

IE9+

var parseHTML = function(str) {
  var tmp = document.implementation.createHTMLDocument();
  tmp.body.innerHTML = str;
  return tmp.body.children;
};

parseHTML(htmlString);

Parse Json

jQuery

$.parseJSON(string);

IE8+

JSON.parse(string);

Trim

jQuery

$.trim(string);

IE9+

string.trim();

Type

jQuery

$.type(obj);

IE8+

Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();

原文:http://youmightnotneedjquery.com/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84961 人气
更多

推荐作者

醉城メ夜风

文章 0 评论 0

远昼

文章 0 评论 0

平生欢

文章 0 评论 0

微凉

文章 0 评论 0

Honwey

文章 0 评论 0

qq_ikhFfg

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文