开发者

JQuery code not working

Why is the following code giving an exception?

function SetText(index, text) {
            try {
                $('p')[index].innerHTML = text;
            }
            catch (ex) {
                alert(ex);
            }
        }

        $(document).ready(SetText(2, 'Damn'));

the exception is:

TypeError: $('p')[index] is undefined

This is my code file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SelectingFromAnElementGroup.aspx.cs" Inherits="JQuery_Intellisence_Test.SelectingFromAnElementGroup" %>

<!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 runat="server">
    <title></title>
    <script src="Javascript/jquery-1.3.2.js" type="text/javascript">
        /// <reference path="jquery-1.3.2-vsdoc.js" />
    </script>
    <script type="text/javascript">
        function SetText(index, text) {
            try {
                $('p')[index].innerHTML = text;
            }
            catch (ex) {
                al开发者_如何学编程ert(ex);
            }
        }

        $(document).ready(SetText(2, 'Damn'));
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>This is 1st Paragraph</p>
            <p>This is 2nd Paragraph</p>
            <p>This is 3rd Paragraph</p>
            <p>This is 4th Paragraph</p>
            <p>This is 5th Paragraph</p>
        </div>
    </form>
</body>
</html>


Try that and tell us what happens:

$(document).ready(function() { SetText(2, 'Damn') });

I think your function is called before the DOM is ready.


<html>
<head>
    <script src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("jquery", "1.3.2");
        function SetText(index, text) {
           try {
               if (typeof $('p')[index] !='indefined') $('p')[index].innerHTML = text;
           } catch (ex) {
                alert(ex);
           }
        }
</script>
</head>
<body>
    <p>Paragraph 0</p>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <script type="text/javascript">
        $(function() {SetText(2, 'Damn');});
    </script>
</body>
</html>

Your code needs to be checked by

if (typeof $('p')[index] !='indefined')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜