Jquery attr ('id' ) 不起作用

标签 jquery alert attr

<!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”!!!! 我不知道这里到底发生了什么。

最佳答案

您必须传递onLoad函数到ready不调用它:

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

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

关于Jquery attr ('id' ) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129647/

相关文章:

javascript - 如何向 jQuery 对象添加新方法?

javascript - 将 HTML 用户输入保存到 Javascript 变量

Android:在通话期间显示通知?

javascript 通过返回 true/false 确认替换

javascript - .prop() 与 .attr()

javascript - 用于查找图像引用的正则表达式

javascript - 如何获取相同类名的每个值?

jquery - 在所有浏览器中使用 &lt;input type ="file"> 时如何使用上传文件的 JQUERY 获取完整路径,为什么 IE、Chrome 返回 "c:/fakepath/filname"?

jquery - 使用 Jquery + Accordion 淡入属性

html - 附加到父级