【问题标题】:finding the length of a form select element using javascript使用javascript查找表单选择元素的长度
【发布时间】:2011-03-06 23:59:42
【问题描述】:

我尝试了几种不同的变体来查找选择元素的长度,但没有任何效果!我不知道为什么,因为有几个网站将这是正确的代码。

这里是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 之类的变体,但没有任何效果!

谢谢。

【问题讨论】:

    标签: javascript forms select


    【解决方案1】:

    执行顺序。您可能正试图在 #opentimes 存在于 DOM 之前对其进行访问。

    尝试将您的 javascript 置于&lt;select&gt;(按源代码顺序)或将其包装在正文的加载事件中。

    第二条建议

    <script type="text/javascript"> 
      onload = function()
      {
        alert(document.getElementById("opentimes").options.length);
      }
    </script>
    

    但请注意 - 如果其他脚本正在使用它,您通常可以覆盖其他“加载”功能。

    【讨论】:

      【解决方案2】:

      您的代码实际上正在运行,但我猜您的代码是在加载 DOM 之前执行的。试试这个,例如:

      <script type="text/javascript"> 
          window.onload = function(){
              alert(document.getElementById("opentimes").options.length);
          };
      </script>
      

      所有包含在window.onload = function(){ ... }; 中的代码都将在加载网页上的 HTML 结构时执行。从那一刻起,您就可以使用document.getElementById() 方法了。

      此外,您可以将代码下移到文档的末尾,但我不建议这样做。太丑了。

      【讨论】:

      • 啊,是的,这就是问题所在!我实际上在一个函数中有警报,但为了简单起见,我以这种方式粘贴了它。我在构建选择之前调用了该函数。更改了顺序,现在可以使用。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多