版本历史
2006 · v1.0
John Resig 发布 jQuery,解决浏览器兼容性噩梦
2013 · v2.0
放弃 IE 6/7/8 支持,体积大幅减小
2016 · v3.0
Promise/A+ 兼容,支持 requestAnimationFrame
2024 · v4.0
彻底放弃 IE,拥抱现代浏览器,FormData 原生支持
经典选择器
$('.demo-box').addClass('highlight');
$('.special').css('background', '#ffd700');
链式调用 · jQuery的灵魂
$('#chainTarget')
.css('background', '#0769ad')
.animate({ paddingLeft: '50px', paddingRight: '50px' }, 300)
.text('链式调用!')
.fadeOut(500)
.fadeIn(500);
动画系统
$('#target').animate({
left: '300px',
opacity: 0.5
}, 1000);
事件处理
在这里点击、双击、移动鼠标试试
$('#eventArea').on('click dblclick mouseenter mouseleave', function(e) {
console.log(e.type);
});
Ajax · 4.0 支持原生 Promise
$.get('/api/data')
.then(data => console.log(data))
.catch(err => console.error(err));
jQuery vs 原生 · 2024年还需要jQuery吗?
| 功能 |
jQuery |
原生 (现代浏览器) |
| 选择元素 |
$('.class') |
document.querySelectorAll('.class') |
| 添加类名 |
$(el).addClass('x') |
el.classList.add('x') |
| Ajax请求 |
$.get(url) |
fetch(url) |
| 事件绑定 |
$(el).on('click', fn) |
el.addEventListener('click', fn) |
| 动画 |
$(el).fadeIn() |
el.animate() / CSS transition |
结论:新项目不需要jQuery了,但老项目升级到4.0是值得的。