【问题标题】:"Object expected" error while calling javascript function调用 javascript 函数时出现“预期对象”错误
【发布时间】:2011-02-23 14:19:56
【问题描述】:

我想根据下拉列表中选择的值更改文本框的可见性。

我已经创建了这样的函数:

function ShowGiftCardSource() {
        var ddlGiftCardSource = document.getElementById('<%=ddlGiftCardSource.ClientID%>');
        var txtGiftCardSource = document.getElementById('<%=txtGiftCardSource.ClientID%>');

        if (ddlGiftCardSource.value == "Other") {
            txtGiftCardSource.style.visibility = "visible";
            txtGiftCardSource.focus();
        }
    }

在 CS 页面中:

ddlGiftCardSource.Attributes.Add("onChange", "OnSelectedIndexChanged();"); 

在控件中:

<asp:DropDownList ID="ddlGiftCardSource" runat="server" Width="151px" onChange="ShowGiftCardSource();">

但我收到以下错误:

Microsoft JScript runtime error: Object expected

有人可以帮我解决吗?

【问题讨论】:

    标签: c# javascript drop-down-menu onchange


    【解决方案1】:

    把后面的代码改成:

    ddlGiftCardSource.Attributes.Add("onChange", "ShowGiftCardSource();");
    

    并从标签中删除onchange

    <asp:DropDownList ID="ddlGiftCardOccasion" runat="server" Width="151px">
    

    标签中的onchange服务器端调用的方法。

    编辑:如果您已经有服务器端方法,您必须首先将 AutoPostBack 添加到下拉列表中,然后在服务器端 onchange 事件中显示文本框:

    <asp:DropDownList ID="ddlGiftCardOccasion" runat="server" Width="151px" OnChange="ShowGiftCardSource" AutoPostBack="True">
    

    在你的 C# 代码后面:

    void ShowGiftCardSource(object sender, EventArgs e) {
      //code.....
      txtGiftCardSource.Visible = true;
    }
    

    当然,去掉ddlGiftCardSource.Attributes.Add 行。

    【讨论】:

    • ddlGiftCardSource 的 onChange 事件。
    • @Knv 你不能同时拥有客户端事件和服务器端事件,这是没有意义的。查看我的编辑。
    • 在服务器端,没有它的事件。我讲述了加载页面时注册的“onChange”。实际上,我在“ShowGiftCardSource()”[JavaScript] 方法上设置了一个断点并执行了它,但是当我从下拉列表中选择一个项目时,什么也没发生。我不明白,为什么会这样?,如果您知道任何替代方案,请建议我。感谢您的回复。
    • 对不起,我完全失去了你。我为您提供了所有选项,无法更好地解释。
    【解决方案2】:

    也许那是因为您在 onChange 处理程序中使用 ShowGiftCardOccasion() 方法,但您的方法名称是 ShowGiftCardSource() ?然后 javascript 就找不到正确名称的方法。

    【讨论】:

    • &lt;asp:DropDownList ID="ddlGiftCardSource" runat="server" Width="151px" onChange="ShowGiftCardSource();"&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多