jquery - Detect jQuery undefined
问题描述
I have this bit of script
$('a').on('click', function () {
var vIDString = this.getAttribute('id');
if (vIDString === undefined) {
//do nothing
alert('Hit undefined')
} else {
var vID = vIDString.substring(8);
}
})
I have tried x === undefined, x === 'undefined', typeof x === undefined, typeof x === 'undefined' and everthing else I can think of, and it happily skips over that and throws 'Unable to get property 'substring' of undefined or null reference'
Any idea what I am doing wrong?
Thank you
解决方案
你永远不会得到undefined。事实上,来自MDN:
getAttribute() 返回元素上指定属性的值。如果给定的属性不存在,则返回的值为 null 或 ""(空字符串);有关详细信息,请参阅注释。
因此,您需要针对 null 或空字符串进行测试:
$('a').on('click', function (e) {
e.preventDefault();
var vIDString = this.getAttribute('id');
if (vIDString == null || vIDString.length == 0) {
//do nothing
console.log('Hit undefined')
} else {
console.log('ID is: ' + vIDString);
//var vID = vIDString.substring(8);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="url">link text with no ID</a><br/>
<a id="IDVALUE" href="url">link text</a>
推荐阅读
- javascript - 如何使用 chrome 开发工具获取 youtube 成绩单 url?
- xsd - xsd复杂类型继承中的限制问题
- python - 尝试使用 Anaconda-navigator 安装 Tensorflow,但在导航器中找不到包
- flutter - 发射状态更改后保持 UI Cubit Flutter
- python - 合并日期时间和范围的数据框
- php - 在 apache2 启动时启动 php 脚本
- snowflake-cloud-data-platform - Infromatica 云 - 由于以下错误,Snowflake 连接器无法从源读取数据:null
- c# - 当 .csproj 被称为 Nuget 包时出现 FileNotFoundException
- javascript - 使用虚拟主机服务器从网站发送电子邮件
- amazon-fire-tv - 为什么我在 FireTV 4K 上设置代理时卡在登录页面