我有一个 Pane ,其中包含一组 javascript 生成的表格,每个表格都有一个唯一的 ID 和 4 个单元格,并且我使用以下 Javascript 代码来设置其中一个表格的背景颜色。它在 Firefox 中运行良好,但在第一次尝试设置背景颜色(在 if 语句中)时,它会使 Safari 崩溃。有什么想法吗?
<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>
最佳答案
如果数组索引不存在,您应该始终测试它们是否存在
例如
<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>
关于javascript - 为什么这个 javascript 会使 safari 崩溃而不是 firefox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1023017/