20,105
stars
+-7+-6+-16
1,702
forks
–
watchers
–
prs
–
issues
–
releases
–
discussions
README
你也许不需要 jQuery (You (Might) Don't Need jQuery)
前端发展很快,现代浏览器原生 API 已经足够好用。我们并不需要为了操作 DOM、Event 等再学习一下 jQuery 的 API。同时由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用场景大大减少。本项目总结了大部分 jQuery API 替代的方法。
示例代码面向当前的常青浏览器(Chrome、Edge、Firefox、Safari)。微软已停止支持 Internet Explorer,所以针对 IE 的兼容写法都已删除。如果仍需要,请查看最后一个兼容 IE 的版本。
目录
1. 翻译
2. Query 选择器
3. CSS & Style
4. DOM 操作
5. Ajax
6. 事件
7. 实用工具
8. Promises
9. 动画
10. 替代品
11. 浏览器支持
翻译
한국어
正體中文
简体中文
Bahasa Melayu
Bahasa Indonesia
Português(PT-BR)
Tiếng Việt Nam
Español
Русский
Кыргызча
Türkçe
Italiano
Français
日本語
Polski
Query 选择器
常用的 class、id、属性 选择器都可以使用 document.querySelector 或 document.querySelectorAll 替代。区别是
document.querySelector 返回第一个匹配的 Element
document.querySelectorAll 返回所有匹配的 Element 组成的静态 NodeList。它支持 forEach,也可以用 Array.from(document.querySelectorAll(selector)) 或 makeArray 里的其他方法转成 Array
如果匹配不到任何 Element,jQuery 返回空的 jQuery 对象,document.querySelectorAll 返回空的 NodeList,而 document.querySelector 返回 null,注意空指针异常。
注意:document.getElementById、document.getElementsByClassName 和 document.getElementsByTagName 比 querySelector 略快,但 getElementsBy 返回的是动态(live)HTMLCollection,会随 DOM 变化而变化。除非实测发现性能瓶颈,否则优先用 querySelector。
- 1.0 选择器查询
js
// jQuery
$('selector');
// Native
document.querySelectorAll('selector');
- 1.1 class 查询
js
// jQuery
$('.class');
// Native
document.querySelectorAll('.class');
// or
document.getElementsByClassName('class');
- 1.2 id 查询
js
// jQuery
$('id');
// Native
document.querySelector('id');
// or
document.getElementById('id');
- 1.3 属性查询
js
// jQuery
$('a[target=_blank]');
// Native
document.querySelectorAll('a[target=_blank]');
- 1.4 后代查询
js
// jQuery
$el.find('li');
// Native
el.querySelectorAll('li');
- 1.5 兄弟及上下元素
+ 兄弟元素
js
// jQuery
$el.siblings();
// Native
[...el.parentNode.children].filter((child) =
child !== el
);
+ 上一个元素
js
// jQuery
$el.prev();
// Native
el.previousElementSibling;
+ 下一个元素
js
// jQuery
$el.next();
// Native
el.nextElementSibling;
+ 之前所有的兄弟元素
js
// jQuery(可选的过滤选择器)
$el.prevAll($filter);
// Native(可选的过滤函数)
function getPreviousSiblings(elem, filter) {
const sibs = [];
while ((elem = elem.previousElementSibling)) {
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
+ 之后所有的兄弟元素
js
// jQuery(可选的过滤选择器)
$el.nextAll($filter);
// Native(可选的过滤函数)
function getNextSiblings(elem, filter) {
const sibs = [];
while ((elem = elem.nextElementSibling)) {
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
过滤函数示例:
js
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
r