jQuery 生态对比
jQuery、jQuery UI、jQuery Mobile 的区别与使用场景
问题
jQuery、jQuery UI、jQuery Mobile 三者有什么区别?各自的使用场景是什么?
解答
jQuery
核心库,提供 DOM 操作、事件处理、Ajax 请求等基础功能。
// DOM 操作
$('#app').addClass('active');
// 事件绑定
$('button').on('click', function() {
console.log('clicked');
});
// Ajax 请求
$.ajax({
url: '/api/data',
method: 'GET',
success: function(data) {
console.log(data);
}
});
// 链式调用
$('.item')
.css('color', 'red')
.fadeIn(300)
.text('Hello');
jQuery UI
基于 jQuery 的 UI 组件库,提供交互组件和视觉效果。
<!-- 引入依赖 -->
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<input type="text" id="datepicker">
<div id="draggable">拖拽我</div>
<div id="sortable">
<div>项目 1</div>
<div>项目 2</div>
<div>项目 3</div>
</div>
// 日期选择器
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd'
});
// 拖拽功能
$('#draggable').draggable();
// 排序功能
$('#sortable').sortable({
update: function(event, ui) {
console.log('顺序已更新');
}
});
// 对话框
$('#dialog').dialog({
modal: true,
buttons: {
'确定': function() {
$(this).dialog('close');
}
}
});
// 动画效果
$('#box').effect('shake', { times: 3 }, 500);
jQuery Mobile
针对移动端的 UI 框架,提供触摸优化的组件。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile.css">
<script src="jquery.js"></script>
<script src="jquery.mobile.js"></script>
</head>
<body>
<!-- 页面结构 -->
<div data-role="page" id="home">
<!-- 头部 -->
<div data-role="header">
<h1>首页</h1>
</div>
<!-- 内容区 -->
<div data-role="content">
<a href="#page2" data-role="button">跳转页面</a>
<!-- 列表视图 -->
<ul data-role="listview" data-inset="true">
<li><a href="#">列表项 1</a></li>
<li><a href="#">列表项 2</a></li>
</ul>
<!-- 折叠面板 -->
<div data-role="collapsible">
<h3>点击展开</h3>
<p>隐藏的内容</p>
</div>
</div>
<!-- 底部导航 -->
<div data-role="footer" data-position="dbpnk">
<div data-role="navbar">
<ul>
<li><a href="#" data-icon="home">首页</a></li>
<li><a href="#" data-icon="gear">设置</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
三者对比
| 特性 | jQuery | jQuery UI | jQuery Mobile |
|---|---|---|---|
| 定位 | 核心库 | 桌面端 UI 组件 | 移动端 UI 框架 |
| 依赖 | 无 | jQuery | jQuery |
| 体积 | ~90KB | ~280KB | ~200KB |
| 主要功能 | DOM/事件/Ajax | 拖拽/日期/对话框 | 触摸/页面切换/移动组件 |
| 使用场景 | 所有 Web 项目 | 桌面端后台系统 | 移动端 Web 应用 |
关键点
- jQuery 是基础库,另外两个都依赖它
- jQuery UI 面向桌面端,提供拖拽、排序、日期选择等交互组件
- jQuery Mobile 面向移动端,通过
data-*属性声明式创建组件 - jQuery Mobile 已停止维护,现代移动端开发推荐使用 Vue/React 等框架
- 三者可以同时使用,但要注意加载顺序和版本兼容性
目录