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

标签: javascriptjquery

解决方案


如果要检查元素是否存在,为什么不使用:

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...")

推荐阅读