jQuery 4.0 移除了许多已废弃的方法和特性
jQuery 4.0 移除了许多已废弃的方法和特性。以下是主要的移除内容:
1. 已废弃的方法移除
类型检测方法
javascript
// 全部移除
$.type() // 用 typeof、Array.isArray() 等替代
$.isArray() // 用 Array.isArray() 替代
$.isFunction() // 用 typeof obj === 'function' 替代
$.isNumeric() // 用 !isNaN(parseFloat(obj)) && isFinite(obj) 替代
$.isEmptyObject() // 用 Object.keys(obj).length === 0 替代
$.isPlainObject() // 需要手动实现或使用其他库
$.isWindow() // 用 obj && obj.window === obj 替代
字符串处理方法
javascript
$.trim() // 用 String.prototype.trim() 替代
$.param() // 用 URLSearchParams 或手动实现
DOM 相关方法
javascript
$.nodeName() // 用 element.nodeName 或 element.tagName 替代
$.holdReady() // 完全移除
$.cssHooks // 部分移除
2. 废弃的 Ajax 方法
javascript
// 这些方法已被移除
$.ajax() 中的 async: false 支持 // 同步请求被移除
$.ajax() 中的 `success`、`error`、`complete` 回调参数
$.ajax() 的 `crossDomain`、`isLocal`、`jsonp` 选项简化
$.event 中的 ajax 事件别名(ajaxSuccess/ajaxError 等)
3. 事件相关移除
javascript
// 已移除
.load() 作为事件快捷方式 // 只能用作 AJAX 方法
.unload() 事件 // 用 beforeunload 替代
.hover() 方法 // 用 .on('mouseenter mouseleave') 替代
// 事件方法移除
$.fn.bind() 和 $.fn.unbind() // 用 .on() 和 .off() 替代
$.fn.delegate() 和 $.fn.undelegate() // 用 .on() 和 .off() 替代
$.fn.toggle() // 移除事件切换功能
$.fn.size() // 用 .length 替代
4. 动画相关移除
javascript
// 已移除
$.fn.toggle() 的动画功能 // 只保留显示/隐藏功能
$.fx.interval // 移除配置
.promise() 的动画特定方法
5. 数据缓存相关
javascript
// $.data() 和 $.removeData() 的行为变化
// 不再自动将字符串转换为 JSON
$.data(elem, "key", "true") // 以前会转为 boolean,现在保持字符串
6. 其他移除
javascript
// 已移除
$.context // 早已废弃
$.support // 移除,用特性检测替代
$.selector // 早已废弃
$.attrFn // 早已废弃
// 移除了对老旧浏览器的支持
IE10 及更早版本的支持
旧版 WebKit 的支持
7. 行为变更
javascript
// 默认行为变化
$(htmlString) // 不再自动执行脚本
$(window).load() // 不再支持
$(document).ready() 简写 $(fn) // 仍然支持,但内部实现优化
8. 迁移建议
创建兼容性补丁
javascript
// 在升级前添加兼容层
if (!$.type) {
$.type = function(obj) {
if (obj === null) return 'null';
if (obj === undefined) return 'undefined';
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
}
使用替代方案
javascript
// 推荐的原生替代方案
const utils = {
isFunction: obj => typeof obj === 'function',
isArray: Array.isArray,
isNumeric: value => !isNaN(parseFloat(value)) && isFinite(value),
isEmptyObject: obj => Object.keys(obj).length === 0,
trim: str => String(str || '').trim()
};
9. 检查清单
升级时检查以下常见问题:
-
$.trim()→.trim() -
$.isFunction()→typeof === 'function' -
$.isArray()→Array.isArray() -
$.type()→typeof或Object.prototype.toString.call() -
$.nodeName()→.nodeName或.tagName -
.bind()/.unbind()→.on()/.off() -
.delegate()/.undelegate()→.on()/.off()
建议使用 jQuery Migrate 插件帮助迁移,它会警告这些已移除的 API 使用。
浙公网安备 33010602011771号