使用 javascript 查找表单选择元素的长度
我尝试了几种不同的变体来查找选择元素的长度,但没有任何效果!我不明白为什么,因为几个网站将其列为正确的代码。
这是 javascript:
<script type="text/javascript">
alert(document.getElementById("opentimes").options.length);
</script>
这是表单:
<form action="eateries.php" method="POST" name="filters">
<select name="opentimes" id="opentimes" onChange="document.forms.filters.submit();">
<option value="now">Open Now</option>
<option value="tonight">Open Tonight</option>
<option value="late">Open Late</option>
<option value="whenever">Open Whenever</option>
</select>
.......
</form>
我知道警报正在工作,因为我已经用简单的字符串对其进行了测试。我尝试过像 document.filters.opentimes.length 和 document.forms.filters.opentimes.length 这样的变体,但没有任何效果!
谢谢。
i've tried several different variations of finding the length of a select element and nothing's working! i can't figure out why, since several websites list this is as the correct code.
here's the javascript:
<script type="text/javascript">
alert(document.getElementById("opentimes").options.length);
</script>
and here's the form:
<form action="eateries.php" method="POST" name="filters">
<select name="opentimes" id="opentimes" onChange="document.forms.filters.submit();">
<option value="now">Open Now</option>
<option value="tonight">Open Tonight</option>
<option value="late">Open Late</option>
<option value="whenever">Open Whenever</option>
</select>
.......
</form>
i know the alert is working because i've tested it with simple strings. i've tried variations like document.filters.opentimes.length and document.forms.filters.opentimes.length but nothing works!
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码实际上是有效的,但我猜你的代码是在 DOM 加载之前执行的。例如,尝试一下:
加载网页上的 HTML 结构时,将执行
window.onload = function(){ ... };
中包含的所有代码。从那时起,您就可以使用document.getElementById()
方法。另外,您可以将代码移至文档末尾,但我不建议这样做。太丑了。
You're code is actually working, but I guess your code is executed before the DOM is loaded. Try this, for example:
All code which is wrapped in
window.onload = function(){ ... };
will be executed when the HTML-structure on the webpage is loaded. From that moment, you can use thedocument.getElementById()
method.Also, you can move your code down to the end of the document, but I wouldn't recommend that. It's ugly.
执行顺序。您可能尝试在#opentimes 存在于 DOM 中之前访问它。
尝试将 JavaScript 放在
第二个建议正在实施
但请注意 - 如果其他脚本正在使用它,您通常可以覆盖其他“加载”功能。
Order of execution. You're probably trying to access #opentimes before it exists in the DOM.
Try either putting your javascript below the
<select>
(in source order) or wrapping it in the body's load event.2nd suggestion in action
But be warned - you can often overwrite other "on load" functionality if other scripts are using it.