为什么textbox onchange事件在asp.net用户控件中没有正确触发?

时间:2012-02-15 20:21:38

标签: javascript asp.net html asp.net-ajax

我有2个文本框,我正在尝试捕获onchange事件。这些文本框位于asp.net更新面板内的用户控件中。每次我更改文本框文本时,都会收到“Microsoft JScript运行时错误:预期的对象”错误,但不提供任何其他有用的信息。

以下是代码:

    <script type="text/javascript">
        function ResetOrientationImage() {
            var width = (+document.getElementById('<%= txtWidth.ClientID %>').value);
            var height = (+document.getElementById('<%= txtHeight.ClientID %>').value);
            if (width > height) {
                document.getElementById('<%= imgOrientation.ClientID %>').src = "images/buttons/Landscape.png";
            } else {
                document.getElementById('<%= imgOrientation.ClientID %>').src = "images/buttons/Portrait.png";
            }
        }
</script>
<asp:TextBox ID="txtWidth" runat="server" Width="50px" onchange="ResetOrientationImage()" Text="0"></asp:TextBox>
<asp:TextBox ID="txtHeight" runat="server" Width="50px" onchange="ResetOrientationImage()" Text="0"></asp:TextBox>
<asp:Image ID="imgOrientation" ImageUrl="~/images/buttons/Portrait.png" runat="server" />

我认为这肯定是javascript的一个问题,但我把这个确切的代码放到一个独立的.aspx页面中,它正确执行而没有错误。

修改 在查看Firebug时,真正的错误是在页面执行时找不到ResetOrientationImage函数。如果我将javascript从用户控件移出到页面本身,它就像我期望的那样工作。为什么javascript不能存在于用户控件中?

2 个答案:

答案 0 :(得分:1)

这里有一些事情:

var width = (+document.getElementById('<%= txtWidth.ClientID %>').value);
var height = (+document.getElementById('<%= txtHeight.ClientID %>').value);

“文档”之前的开头的“+”无效。

widthheight将成为字符串。你需要把它们整数:

var width = parseInt(document.getElementById('<%= txtWidth.ClientID %>').value);

另外 - 请详细说明HTML 输出,而不是.NET 来源。问题出在客户端,而不是服务器上。

答案 1 :(得分:0)

我偶然发现了这个问题给了我答案:

Javascript object "is not defined" error after ScriptManager.RegisterClientScriptInclude

我将我的javascript函数移动到外部文件中,并在后面的用户控件代码中引用它,如下所示:

    ScriptManager sm = ScriptManager.GetCurrent(Page);
    ScriptReference sr = new ScriptReference("~/scripts/ResetOrientationImage.js");
    if (!sm.Scripts.Contains(sr))
       sm.Scripts.Add(sr);