2011-02-26 88 views
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> 
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(onLoad()); 

     function onLoad() { 
      alert($("#wcontrol_subtable0").attr('id')); 
     } 
    </script> 
    <title></title> 
</head> 
<body> 
    <form name="form1" method="post" action="Default.aspx" id="form1"> 
    <div id="wcontrol_pnlMenu"> 
     <table border="0"> 
      <tr> 
       <td> 
        <table id="wcontrol_subtable0" class="class1" cellspacing="0" cellpadding="0" border="0" 
         style="border-collapse: collapse;"> 
         <tr id="wcontrol_subtable0_th"> 
          <th> 
           Parameters 
          </th> 
         </tr> 
         <tr> 
          <td> 
          </td> 
         </tr> 
        </table> 
       </td> 
      </tr> 
     </table> 
    </div> 
    </form> 
</body> 
</html> 

它看起來很正常,問題是警報方法出現「null」!!!! 我不知道這裏發生了什麼。Jquery attr('id')不工作

回答

3

你必須onLoad功能ready不叫它:

$(document).ready(onLoad); 
// no parenthesis ----^ 

否則你會的onLoad返回值傳遞給ready方法,即onLoad被調用,在DOM準備好之前。

+0

Maaaaan !!!你是英雄!那讓我瘋狂。謝謝菲利克斯! – Lug 2011-02-26 20:55:44

+1

@Lug:不客氣:)請記住,函數是JavaScript中的第一類公民。你可以按名稱引用它們。添加括號會調用它們。 – 2011-02-26 20:57:07

0

您在準備好的活動中使用返回值onLoad

這意味着onLoad函數被調用立即(找出returnv ALUE是什麼),並且你正在尋找不存在(因爲DOM該元素的元素尚未建造,那時間)。

關閉()以傳遞函數而不是其返回值。