开发者

Jquery attr('id') is not working

开发者 https://www.devze.com 2023-02-14 03:43 出处:网络
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<!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>
                  开发者_如何学JAVA      </tr>
                        <tr>
                            <td>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

It looks like very normal, the issue is that the alert method comes out with "null"!!!! I don't know what is really going on here.


You have to pass the onLoad function to ready, not call it:

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

Else you will pass the return value of onLoad to the ready method, i.e. onLoad is called and that before the DOM is ready.


You are using the return value of onLoad in the ready event.

This means that the onLoad function is called immediately (to find out what the returnv alue is) and the element that you are looking for does not exist (since the DOM for that element hasn't been constructed that that time).

Take the () off to pass the function instead of its return value.

0

精彩评论

暂无评论...
验证码 换一张
取 消