首页 > 解决方案 > 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

标签: jqueryasp.net-mvc-5

解决方案


你永远不会得到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>


推荐阅读