开发者

javascript - dom searching for id returns an error - how to handle?

    for (i=1; i<=4; i++) {
        try {
           timer = document.getElementById("timer"+i).parentNode.parentNode.parentNode.childNodes[1].childNodes[0].childNodes[0].className;
        }
        catch(e) {
           FM_log("aguardaReforcos()", "ERRO - timer"+i);
        }
    ...

I have to it this way with try becau开发者_Go百科se otherwise I get a crash when it doesn´t find document.getElementById("timer"+i).parentNode.parentNode.parentNode.childNodes[1].childNodes[0].childNodes[0].className

is there another way of preventing this type of crash?


You can use each of the properties in turn without causing a crash, but the code will of course contain a whole lot of tests:

var timer = document.getElementById("timer"+i);
if (timer) {
  timer = timer.parentNode;
  if (timer) {
    timer = parentNode;
    if (timer) {
      // and so on...
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜