【问题标题】:Getting Id of a .net dropdownlist in javascript on client click在客户端单击时在 javascript 中获取 .net 下拉列表的 ID
【发布时间】:2009-05-14 17:41:35
【问题描述】:

我需要获取下拉列表(ASP.Net 控件)的 ID,以便判断是否已选择项目。

现在我正在尝试将下拉列表的计数写入警报框,如下所示:

OnClientClick="alert(document.getElementID('<%=ListBox1.ClientID %>').options.length)

我得到的错误是“需要文件”。

【问题讨论】:

    标签: .net asp.net javascript vb.net drop-down-menu


    【解决方案1】:

    首先让我们将代码中的getElementID 更正为getElementById

    OnClientClick="alert(document.getElementById('<%=ListBox1.ClientID %>').options.length);"
    

    如果您想知道选择了哪个项目,请使用selectedIndex 属性:

    OnClientClick="alert(document.getElementById('<%=ListBox1.ClientID %>').selectedIndex);"
    

    如果您想要选项的值而不是索引,请使用带有索引的选项集合:

    OnClientClick="var s=document.getElementById('<%=ListBox1.ClientID %>');alert(s.options[s.selectedIndex].value);"
    

    编辑:
    如果您尝试使用它的控件不是服务器控件,这将起作用,例如:

    <input type="button" onclick="alert(document.getElementById('<%=ListBox1.ClientID %>').options.length);" />
    

    由于您有一个服务器控件,因此您不能在控件内使用脚本标记 ()。您必须从后面的代码中设置属性:

    TheButton.OnClientClick = "alert(document.getElementById('" + ListBox1.ClientID + "').options.length);";
    

    【讨论】:

    • 仍然需要对象。
    • 我明白了。问题在于 脚本标签。我编辑了答案。
    【解决方案2】:

    请使用 document.getElementById 而不是 document.getElementId

    【讨论】:

      【解决方案3】:

      我的 javascript 有点生疏,但你不能使用“this”关键字吗? 类似:

      OnClientClick="alert(this.options.length);"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 2012-12-04
        • 1970-01-01
        相关资源
        最近更新 更多