当前位置: 代码迷 >> JavaScript >> 为什么用document.getElementById得不到对象总是返回null呢?什么原因,该如何处理
  详细解决方案

为什么用document.getElementById得不到对象总是返回null呢?什么原因,该如何处理

热度:261   发布时间:2012-03-09 16:54:57.0
为什么用document.getElementById得不到对象总是返回null呢?什么原因

for   (var   d   =   0;   d   <   4;   d++){
    var   t_obj_current   =   document.getElementById( "t "+d);
    if   (t_obj_current   !=   null){
          t_obj_current.className= "affiche_tab_nosel ";
    }
}

<table   cellpadding= "0 "   cellspacing= "0 "   border= "0 ">
    <tr>
        <td   width= "20px "   height= "20px "   align= "center "   class= "affiche_tab_sel "   id= "t0 "> 今 </td>
        <td   width= "2px "> </td>
        <td   width= "20px "   align= "center "   class= "affiche_tab_nosel "   id= "t1 "> 昨 </td>
    <td   width= "2px "> </td>
    <td   width= "20px "   align= "center "   class= "affiche_tab_nosel "   id= "t2 "> 前 </td>
    <td   width= "2px "> </td>
    <td   width= "20px "   align= "center "   class= "affiche_tab_nosel "   id= "t3 "> ... </td>
</tr>
</table>

------解决方案--------------------
for (var d = 0; d < 4; d++){
var t_obj_current = document.getElementById( "t "+d);
if (t_obj_current != null){
t_obj_current.className= "affiche_tab_nosel ";
}
}
这段js代码应该放在下面执行。放在上面的时候页面初始化还没有完成,程序当然不知道有t1、t2这些对象了
------解决方案--------------------
呵呵,楼上的正解,我的代码全部放在下面
------解决方案--------------------
不放在下面也可以:
<html>
<head>
<script type= "text/javascript ">
function wiliner()
{
for (var d = 0; d < 4; d++){
var t_obj_current = document.getElementById( "t "+d);
alert(t_obj_current);
if (t_obj_current != null){
t_obj_current.className= "affiche_tab_nosel ";
}
}
}

</script>
</head>
<body onload= "wiliner(); ">
<table cellpadding= "0 " cellspacing= "0 " border= "0 ">
<tr>
<td width= "20px " height= "20px " align= "center " class= "affiche_tab_sel " id= "t0 "> 今 </td>
<td width= "2px "> </td>
<td width= "20px " align= "center " class= "affiche_tab_nosel " id= "t1 "> 昨 </td>
<td width= "2px "> </td>
<td width= "20px " align= "center " class= "affiche_tab_nosel " id= "t2 "> 前 </td>
<td width= "2px "> </td>
<td width= "20px " align= "center " class= "affiche_tab_nosel " id= "t3 "> ... </td>
</tr>
</table>
  相关解决方案