javascript - How to check for null or undefined methods?
问题描述
Somewhere along the line jQuery
changed it's handling of non-existent elements. Assume #nearby
element does not exist, then
console.log($('#nearby').html());
A) In jQuery <= 1.7.2
, it prints out null
B) In jQuery > 1.7.2
, it prints out undefined
I am trying to support checking for both cases. The following works:
if ($('#nearby').html() === null || $('#nearby').html() === undefined)
{
console.log('nothing here');
}
Is there a less ugly way of checking for null
or undefined
methods? I tried a boolean check:
(`if ($('#nearby').html()))` ...
But it didn't work. So, Is there a better way?
Note that this is not a check for undefined/null variables, for which there are a million answers on SO.
解决方案
如果要检查元素是否存在,为什么不使用:
If (!$('#nearby').length)
{
console.log("nothing here...")
}
console.log(!$('#nearby').length);
if (!$('#nearby').length)
console.log("#nearby do not exists!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
另一方面,如果元素存在并且您想检查该元素是否有可用的方法,那么您可以使用typeof
if ($('#nearby').length && typeof($('#nearby').html) !== "function")
console.log("html() is undefined!");
if ($('#nearby').length && !typeof($('#nearby').foo) !== "function")
console.log("foo() is undefined!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nearby"></div>
因此,总而言之,如果您想检查元素是否不存在或某些方法是否可用,您可以执行此操作。
if (!$('#nearby').length || typeof($('#nearby').foo) !== "function")
console.log("Nothing here...")
推荐阅读
- r - 汇总条件和加起来为 0
- jquery - 在 .js 文件中 document.ready() 没有先触发
- web-scraping - 使用 IMPORTXML 将 Yahoo Finance 中的行业信息抓取到 Google 表格中
- python - 如何从另一个函数访问返回的函数值
- android - Android Kotlin - Recyclerview 检测滑动到 onBindViewHolder 内的下一个/上一个项目
- javascript - 从 firebase 实时数据库中获取 JSON 数据
- git - SVN - 在重新创建存储库结构时合并历史记录
- python - anaconda提示中的Matplotlib目录错误?
- php - mkdir():权限被拒绝 权限已设置
- reactjs - 使用 Firebase 在 React Native Expo 应用程序中验证登录页面,但必须单击按钮两次才能执行完整功能