在js中捕获null对象

catch null object in js

本文关键字:null 对象 js      更新时间:2023-09-26

如何捕捉对象为null或不是对象。事实上,我已经写了这行如果条件解决它,但没有工作。

但是生成错误:-"object is null or not a object"

var preWynum = "";
function paint(Wynum)
{
    // alert("Wynum:"+Wynum +", preWynum:"+preWynum);
    if(document.getElementById(preWynum) && document.getElementById(Wynum))
    {
      document.getElementById(preWynum).style.backgroundColor='white';
      document.getElementById(Wynum).style.backgroundColor='yellow';
    }
   preWynum = Wynum; 
}

我不相信它为什么不运行。还有其他想法吗?

preWynum和Wynum是tr(表行)的id。

我想将背景颜色设置为黄色到当前选定的行(id为Wynum)。

错误是因为您正在将一个对象(不存在)传递给getElementById(),而它需要一个字符串:

// Put quotes around 'preWynum' and 'Wynum'
if(document.getElementById('preWynum') && document.getElementById('Wynum'))
{
  document.getElementById('preWynum').style.backgroundColor='white';
  document.getElementById('Wynum').style.backgroundColor='yellow';
}