为 null 或未定义,而不是函数对象

is null or undefined, not a Function object

本文关键字:函数 对象 null 未定义      更新时间:2023-09-26

>我有两个JavaScript函数:

function DisplayErrorMessage(fieldElement, messageElement, message) {
  alert(fieldElement.name);
  if(canFocus(fieldElement)){
    //fieldElement.focus();
    if(fieldElement.type =="text") {
      fieldElement.select();
    }
  }
  messageElement.style.backgroundColor='red';
  messageElement.innerText = message;  
}

以及调用此函数的函数:

function CheckForm(obj, optMsgDiv) {
  if(obj != "") {
    return true;
  } else {
    if(optMsgDiv != "") {
      var messageObj = document.getElementById(optMsgDiv);
      var clearObj = document.getElementById("refUpdMethod");
      var message = getErrorMsg();
      DisplayErrorMessage(clearObj, messageObj, message);
    }
  }
  return false;
}
在一个构建中

,它工作得很好,但是在我的主构建中,我得到了错误:属性"显示错误消息"的值为 null 或未定义,而不是函数对象。

您在哪里看到此错误消息?在某些 IDE 中还是在浏览器中?

看起来找不到显示错误消息函数。如果它和CheckForm都在同一个js文件中,这有点奇怪,也许还有其他一些代码使解析失败。

如果它们位于不同的文件中,请确保这些文件由 Web 服务器正确提供。

若要避免此错误,请始终在使用资源之前验证资源是否可用:if('function' == typeof DisplayErrorMessage){ DisplayErrorMessage(...); }if('function' != typeof DisplayErrorMessage) return;

此外,请避免将对象与空字符串进行比较。而不是obj != ""使用'object' == typeof obj.

更新:正如fsgale所说,也许文件以错误的顺序包含在内。若要避免此错误,请避免在加载 js 文件后立即执行代码。在文件正文中,只需定义函数和类,然后使用加载页面后执行的代码来实例化对象并执行函数。这样做可确保在代码运行时加载所有 js 文件,并使页面呈现速度更快。对于 jQuery,你可以这样做:

if('function' == typeof $)
    $(document).ready(init);
function init(){
    if('function' != typeof $) return;
    // init my stuff
}

此外,如果可能,请始终在 HTML 文档的末尾包含 js 文件,就在 </body> 之前。