jQuery发布比较早,那时js比较弱。现在浏览器标准越来越明确,js语言也在不断完善,jquery中的很多函数已经看上去有些多余了。如果非常在意网页加载速度,jquery可以不用,用纯js即可。
jQuery是非常优秀的工具,它能让我们开发项目时变得更容易。
但如果你想从零开始开发一个全新的项目,你应该考虑一下你的项目是否真的需要引入jQuery。也许你只需要几行技巧性的代码就能解决问题。如果你的项目是面向最新的现代浏览器,你真的可以考虑其它的一些简单的技术来代替jQuery。
浏览器的进步给我们带来了很多先进的JavaScript特征,新出现的原生内置(native)JavaScript功能可以很大程度的实现jQuery提供的功能。如果你能了解这些JavaScript新技术,就能在很多地方用纯JavaScript实现以前需要jQuery才能实现的技术。
第一部分:元素操作
1. Add Class
$(el).addClass(className);
el.classList.add(className);
2. After
$(el).after(htmlString);
el.insertAdjacentHTML('afterend', htmlString);
3. Append
$(parent).append(el)
parent.appendChild(el)
4. Before
$(el).before(htmlString)
el.insertAdjacentHTML("beforebegin",htmlString)
5. Children
$(el).chilren()
el.children
6. Clone
$(el).clone()
el.cloneNoe(true)
7. Contains
$.contains(el,child)
el!==child&&el.contains(child)
8.ContainsSelector
$(el).find(selector).length
el.querySelector(selector)!=null
9. Each
$(sel).each(function(i,el){
})
var elements=document.querySelector(sel)
Array.prototype.forEach.call(elements,function(el,i){
})
10. Empty
$(el).empty()
el.innerHTML=""
11. Filter
$(sel).filter(filterFunc)
var elements=document.querySelector(sel)
Arrays.prototype.filter.call(elements,filterFunc)
12. find
$(el).find(sel)
el.querySelectorAll(sel)
13. 元素定位
$(sel)
document.querySelector(sel)
document.querySelectorAll(sel)
14. 获取属性值
$(el).attr("value")
el.getAttribute("value")
15. html
$(el).html()
el.innerHTML
16. outerHtml
$("<div>").append($(el).clone).html()
el.outerHtml
17. CSS
$(el).css("width")
getComputedStyle(el)['width']
18. text
$(el).text()
el.textContent
19. hasClass
$(el).hasClass(className)
el.classList.contains(className)
20. 元素比较
$(el).is($(another))
el==another
21. 比较类名
$(el).is('.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');
22. next
$(el).next();
el.nextElementSibling
23. offset
$(sel).offset()
el=document.querySelector(sel)
el.getBoundingClientRect()
24. offsetParent
$(el).offsetParent()
el.offsetParent||el
25. outerHeight
$(el).outerHeight
el.offsetHeight
outerWidth is same as outerHeight
26. outerHeight with margin
$(el).outerHeight(true)
function outerHeight(el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}
outerHeight(el);
27. outerWidth with margin is same to outerHeight
28. parent
$(el).parent()
el.parentNode
29. position
$(el).position()
left=el.offsetLeft,top=el.offsetTop
30. position relative to viewport
$(el).offset()
{
top: offset.top - document.body.scrollTop,
left: offset.left - document.body.scrollLeft
}
el.getBoundingClientRect()
31. prepend
$(parent).prepend(el);
parent.insertBefore(el, parent.firstChild);
32. prev
$(el).prev()
el.previousElementSibling
33. remove
$(el).remove()
el.parentNode.removeChild(el)
34. remove class
$(el).removeClass(className)
el.classList.remove(className)
35. replace from html
$(el).replaceWith(htmlString)
el.outerHTML=htmlString
36. 设置属性
$(el).attr('value',3)
el.setAttribute('value',3)
37. html
$(el).html(htmlString)
el.innerHTML=htmlString
38. set style
$(el).css("width","20px")
el.style.borderWidth="20px"
39. set text
$(el).text(str)
el.textContent=str
40. siblings
$(el).siblings()
var siblings = Array.prototype.slice.call(el.parentNode.children);
Array.prototype.filter.call(el.parentNode.children, function(child){
return child !== el;
});
41. toggle class
$(el).toggleClass(className)
el.classList.toggle(className)
第二部分:事件
1. 移除事件处理器
$(el).off(eventName, eventHandler);
el.removeEventListener(eventName, eventHandler);
2. 添加事件处理器
$(el).on(eventName, eventHandler);
el.addEventListener(eventName, eventHandler);
3. 加载完毕回调函数
$(document).ready(function(){
});
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
4. 触发事件
$(el).trigger('my-event', {some: 'data'});
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);
第三部分:技巧
1. 数组遍历
$.each(array, function(i, item){
});
array.forEach(function(item, i){
});
2. 深度扩展
$.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);
3. now
$.now()
Date.now()
4. ajax get
jquery 略
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();
5. ajax post
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);
第四部分:特效
1.淡出
$(el).fadeIn()
el.classList.add('show');
el.classList.remove('hide');
.show {
transition: opacity 400ms;
}
.hide {
opacity: 0;
}
2. 隐藏
$(el).hide()
el.style.display='none'
3. 显示
$(el).show()
el.style.display=''