简体   繁体   中英

why does this javascript crash safari but not firefox?

I have a pane with a set of javascript-generated tables, each with a unique ID and 4 cells, and I use the following Javascript code to set the background color for one of these tables. It works fine in Firefox, but it crashes Safari the first time it tries to set the background color (in the if statement). Any ideas why?

<script language='Javascript'>
  function colortree(source) {
    var el=parent.frames['tree-pane'].document.getElementsByTagName('table');
    for (var i=0;i<el.length;i++) {
        var id = el[i].id;
        if (id) {
           var cell = el[i].getElementsByTagName('td')[3];
           if (id == source) { cell.style.backgroundColor = 'yellow' }
           else { cell.style.backgroundColor = 'white' };
        }
    }
    return false;
  }
</script>

You should always test the existence of array indices if there's any chance they don't exist

eg

<script language='Javascript'>
  function colortree(source) {
    var cells, cell, id;
    var el=parent.frames['tree-pane'].document.getElementsByTagName('table');
    for (var i=0;i<el.length;i++) {
        id = el[i].id;
        if (id) {
           cells = el[i].getElementsByTagName('td');
           if (cells[3]) {
               cell = cells[3];
               if (id == source) { cell.style.backgroundColor = 'yellow' }
               else { cell.style.backgroundColor = 'white' };
           }
        }
    }
    return false;
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM