【问题标题】:Jquery attr('id') is not workingJquery attr('id') 不起作用
【发布时间】:2011-02-26 20:48:35
【问题描述】:
<!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>

看起来很正常,问题是alert方法出来的是“null”!!!! 我不知道这里到底发生了什么。

【问题讨论】:

    标签: jquery alert attr


    【解决方案1】:

    你必须将onLoad函数传递ready不要调用它:

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

    否则,您会将onLoad返回值传递给ready 方法,即在DOM 准备好之前调用onLoad

    【讨论】:

    • @Lug:不客气 :) 请记住,函数是 JavaScript 中的一等公民。您可以仅按名称引用它们。添加括号将调用它们。
    【解决方案2】:

    您在 ready 事件中使用了onLoad返回值

    这意味着onLoad 函数被调用立即(找出返回值是什么)并且您要查找的元素不存在(因为该元素的 DOM那个时候还没有建造)。

    关闭() 以传递函数而不是其返回值。

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2012-08-16
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      相关资源
      最近更新 更多