JQuery代码无法正常工作

时间:2009-11-02 10:21:01

标签: jquery

为什么以下代码会出现异常?

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

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

例外是:

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

这是我的代码文件:

<%@ 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) {
                alert(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>

2 个答案:

答案 0 :(得分:3)

试试并告诉我们会发生什么:

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

我认为在DOM准备好之前调用了你的函数。

答案 1 :(得分:0)

<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>

您的代码需要通过

进行检查
if (typeof $('p')[index] !='indefined')