jQuery检测undefined失效,点击a标签报substring属性获取错误求排查
Hey there! Let's break down why your code is throwing that error and how to fix it.
The Root Cause
When you use this.getAttribute('id') on an <a> tag that doesn't have an id attribute, it returns null, not undefined. All the checks you tried were targeting undefined, so none of them caught the null case. That's why your code skipped the if block, tried to run substring() on null, and threw the "Unable to get property 'substring' of undefined or null reference" error.
Let's recap why your existing checks failed:
x === undefined: Fails becausevIDStringisnull, notundefinedx === 'undefined': Fails because this checks if the value is the string"undefined", which it never istypeof x === undefined: Fails becausetypeofalways returns a string, so this compares a string toundefined(never true)typeof x === 'undefined': Fails becausetypeof nullreturns"object", not"undefined"
Fixed Code Examples
Here are two reliable ways to fix this:
Option 1: Check for both null and undefined
Explicitly handle both possible "missing ID" values:
$('a').on('click', function () { var vIDString = this.getAttribute('id'); if (vIDString === null || vIDString === undefined) { alert('Hit missing ID!'); } else { var vID = vIDString.substring(8); // Add your logic for vID here } })
Option 2: Use the native id property (simpler)
The DOM element's native id property returns an empty string ("") if no ID exists, which is easier to check with a simple truthy/falsy check:
$('a').on('click', function () { var vIDString = this.id; if (!vIDString) { // Catches empty string, null, and undefined alert('Hit missing ID!'); } else { var vID = vIDString.substring(8); // Add your logic for vID here } })
Either approach will prevent the error by ensuring you only run substring() when you have a valid ID string to work with.
内容的提问来源于stack exchange,提问作者gchq

