jQuery是非常优秀的工具,它能让我们开发项目时变得更容易。
但如果你想从零开始开发一个全新的项目,你应该考虑一下你的项目是否真的需要引入jQuery。也许你只需要几行技巧性的代码就能解决问题。如果你的项目是面向最新的现代浏览器,你真的可以考虑其它的一些简单的技术来代替jQuery。
浏览器的进步给我们带来了很多先进的JavaScript特征,新出现的原生内置(native)JavaScript功能可以很大程度的实现jQuery提供的功能。如果你能了解这些JavaScript新技术,就能在很多地方用纯JavaScript实现以前需要jQuery才能实现的技术。
$.getJSON('/my/url', function(data) {
});
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.responseText);
} else {
// Error :(
}
}
};
request.send();
request = null;
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();
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
$.ajax({
type: 'POST',
url: '/my/url',
data: data
});
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);
$.ajax({
type: 'GET',
url: '/my/url',
success: function(resp) {
},
error: function() {
}
});
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.responseText;
} else {
// Error :(
}
}
};
request.send();
request = null;
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();
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
$(el).fadeIn();
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);
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);
el.classList.add('show');
el.classList.remove('hide');
.show {
transition: opacity 400ms;
}
.hide {
opacity: 0;
}
$(el).addClass(className);
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
el.classList.add(className);
$(el).after(htmlString);
el.insertAdjacentHTML('afterend', htmlString);
$(el).before(htmlString);
el.insertAdjacentHTML('beforebegin', htmlString);
$(el).children();
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]);
}
el.children
$(el).find(selector).length;
el.querySelector(selector) !== null
$(selector).each(function(i, el){
});
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){
});
var elements = document.querySelectorAll(selector);
Array.prototype.forEach.call(elements, function(el, i){
});
$(el).empty();
while(el.firstChild)
el.removeChild(el.firstChild);
el.innerHTML = '';
$(selector).filter(filterFn);
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);
Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
$('.my #awesome selector');
document.querySelectorAll('.my #awesome selector');
$(el).css(ruleName);
// Varies based on the properties being retrieved, some can be retrieved from el.currentStyle
// https://github.com/jonathantneal/Polyfills-for-IE8/blob/master/getComputedStyle.js
getComputedStyle(el)[ruleName];
$(el).text();
el.textContent || el.innerText
el.textContent
$(el).hasClass(className);
if (el.classList)
el.classList.contains(className);
else
new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
el.classList.contains(className);
$(el).is('.my-class');
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');
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');
$(el).next();
// nextSibling can include text nodes
function nextElementSibling(el) {
do { el = el.nextSibling; } while ( el && el.nodeType !== 1 );
return el;
}
el.nextElementSibling || nextElementSibling(el);
el.nextElementSibling
$(el).offset();
var rect = el.getBoundingClientRect()
{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
$(el).outerHeight(true);
function outerHeight(el) {
var height = el.offsetHeight;
var style = el.currentStyle || getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}
outerHeight(el);
function outerHeight(el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}
outerHeight(el);
$(el).outerWidth(true);
function outerWidth(el) {
var width = el.offsetWidth;
var style = el.currentStyle || getComputedStyle(el);
width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
}
outerWidth(el);
function outerWidth(el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);
width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
}
outerWidth(el);
var offset = el.offset();
{
top: offset.top - document.body.scrollTop,
left: offset.left - document.body.scrollLeft
}
el.getBoundingClientRect()
$(el).prev();
// prevSibling can include text nodes
function previousElementSibling(el) {
do { el = el.previousSibling; } while ( el && el.nodeType !== 1 );
return el;
}
el.previousElementSibling || previousElementSibling(el);
el.previousElementSibling
$(el).removeClass(className);
if (el.classList)
el.classList.remove(className);
else
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
el.classList.remove(className);
$(el).css('border-width', '20px');
// Use a class if possible
el.style.borderWidth = '20px';
$(el).text(string);
if (el.textContent !== undefined)
el.textContent = string;
else
el.innerText = string;
el.textContent = string;
$(el).siblings();
var siblings = Array.prototype.slice.call(el.parentNode.children);
for (var i = siblings.length; i--;) {
if (siblings[i] === el) {
siblings.splice(i, 1);
break;
}
}
Array.prototype.filter.call(el.parentNode.children, function(child){
return child !== el;
});
$(el).toggleClass(className);
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = -1;
for (var i = classes.length; i--;) {
if (classes[i] === className)
existingIndex = i;
}
if (existingIndex >= 0)
classes.splice(existingIndex, 1);
else
classes.push(className);
el.className = classes.join(' ');
}
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(' ');
}
el.classList.toggle(className);
$(el).off(eventName, eventHandler);
function removeEventListener(el, eventName, handler) {
if (el.removeEventListener)
el.removeEventListener(eventName, handler);
else
el.detachEvent('on' + eventName, handler);
}
removeEventListener(el, eventName, handler);
el.removeEventListener(eventName, eventHandler);
$(el).on(eventName, eventHandler);
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function(){
handler.call(el);
});
}
}
addEventListener(el, eventName, handler);
el.addEventListener(eventName, eventHandler);
$(document).ready(function(){
});
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
$(el).trigger('my-event', {some: 'data'});
// Custom events are not natively supported, so you have to hijack a random
// event.
//
// Just use jQuery.
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);
$(el).trigger('change');
if (document.createEvent) {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
} else {
el.fireEvent('onchange');
}
// 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);
$.each(array, function(i, item){
});
function forEach(array, fn) {
for (i = 0; i < array.length; i++)
fn(array[i], i);
}
forEach(array, function(item, i){
});
array.forEach(function(item, i){
});
$.extend(true, {}, objA, objB);
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')
deepExtend(out[key], obj[key]);
else
out[key] = obj[key];
}
}
}
return out;
};
deepExtend({}, objA, objB);
$.proxy(fn, context);
fn.apply(context, arguments);
fn.bind(context);
$.extend({}, objA, objB);
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);
$.inArray(item, array);
function indexOf(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item)
return i;
}
return -1;
}
indexOf(array, item);
array.indexOf(item);
$.isArray(arr);
isArray = Array.isArray || function(arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
}
isArray(arr);
Array.isArray(arr);
$.map(array, function(value, index){
});
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){
});
array.map(function(value, index){
});
$.parseHTML(htmlString);
var parseHTML = function(str) {
var el = document.createElement('div');
el.innerHTML = str;
return el.children;
};
parseHTML(htmlString);
var parseHTML = function(str) {
var tmp = document.implementation.createHTMLDocument();
tmp.body.innerHTML = str;
return tmp.body.children;
};
parseHTML(htmlString);
$.trim(string);
string.replace(/^\s+|\s+$/g, '');
string.trim();
$.type(obj);
Object.prototype.toString.call(obj)
.replace(/^\[object (.+)\]$/, "$1")
.toLowerCase();