开发者

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

开发者 https://www.devze.com 2023-01-04 12:18 出处:网络
for (i=1; i<=4; i++) { try { timer = document.getElementById(\"timer\"+i).parentNode.parentNode.parentNode.childNodes[1].childNodes[0].childNodes[0].className;
    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

精彩评论

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