这篇文章主要介绍了 jQuery 判断对象是否存在的方法, 对比分析了纯 JavaScript 与 jQuery 实现判断对象是否存在的功能区别, 是非常实用的技巧, 需要的朋友可以参考下.
一, jQuery 判断对象是否存在
1, 方法一
在 jQuery 中, var obj = $("#id") 无论 id 这个控件是否存在, 都是返回 object, 所以需要通过 length 来判断.
- (推荐学习: jQuery 教程手册 https://www.html.cn/doc/jquery/ )
- if ($('#target_obj_id').length> 0) {
- // 如果大于 0 标识 id 为 target_obj_id 的对象存在, 否则不存在
- // 对象存在的处理逻辑
- } else {
- // 对象不存在的处理逻辑
- }
2, 方法二
- if ($('#target_obj_id')[0]) {
- // 对象存在的处理逻辑
- } else {
- // 对象不存在的处理逻辑
- }
二, 传统 JavaScript 的写法
- obj = document.getElementById("someID");
- if (obj){
- obj.innerText("hi");
- }
本文来自 jQuery 答疑 https://www.html.cn/qa/jquery/ 栏目, 欢迎学习!
来源: http://www.css88.com/qa/jquery/15432.html