首先让我们将代码中的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);";