【问题标题】:getting the value of the selected DropDown menu option获取所选下拉菜单选项的值
【发布时间】:2023-03-05 20:48:01
【问题描述】:

所以我知道有很多关于此的帖子并且我阅读了它们,但是之前的帖子中推荐的解决方案不起作用。

我有一个动态创建下拉菜单的功能。这里是:

function date(start, end) {

    output ="";
    for(i=start;i<=end;i++)
    {
    output += "<option value='"+i+"'>"+i+"</option>";
    }

    document.write(output);

}

我这样称呼它:

Month:
        <select name="mm" id="mm" disabled onchange="activateDate();">
            <script type="text/javascript">
                date(1,12);
            </script>
        </select>

注意:activateDay 只是更改下一个下拉菜单中禁用的属性,因为您应该先选择一年,然后是一个月,然后是一天。

当我尝试获取月份的选定值以便我可以给一个月的天数(1 月 31 天,2 月 28 天)时,如下所示:

var a = document.getElementById("mm");
var month = a.options[a.selectedIndex].value;

如果我将此变量用于查找月份并返回天数的开关,那么我将天数提供给我的 date() 我会得到一个空的日期下拉菜单。 chrome 中的 Javascript 控制台这样说:

未捕获的类型错误:无法读取 null 的属性“选项”

并指出这一行:

var month = a.options[a.selectedIndex].value;

那我做错了什么?

【问题讨论】:

  • 你应该避免document.write。请参阅the spec中的警告
  • 是的,我知道,但是我们的老师告诉我们要使用它,我已经听说过很多......
  • 有这样的老师,我会试着拿回我的钱,然后去上另一门课
  • 我在公立学校...

标签: javascript drop-down-menu


【解决方案1】:

错误

Cannot read property 'options' of null

表示aa.options[a.selectedIndex].value 中为空。

由于您有一个带有id="mm" 的元素,请检查:

  • 一些脚本劫持了window.document
  • 一些脚本劫持了document.getElementById
  • 某些脚本删除了您的选择,或更改了其id
  • 在将选择加载到 DOM 之前使用 var a = document.getElementById("mm")

可能是最后一个,尝试在onload 事件中运行您的代码,或者在关闭&lt;/body&gt; 之前放置您的脚本。

【讨论】:

  • 劫持是什么意思?
  • @Jakob 我的意思是document.getElementById = function(){ return null; }
  • 并且使用 onload 对我来说毫无意义,因为我不知道文件加载时用户想要选择哪个月份
  • @Jakob 我不明白。您知道文档加载期间的月份,但加载后不知道?
  • 当我调用我的函数时我不理解你的代码,你命名函数我需要月份作为参数。我为什么要在document.getElementById 中调用它,它应该如何工作。
【解决方案2】:

尝试使用此代码

var month = a.options[a.selectedIndex-1].value;

【讨论】:

  • a 为空,如日志中所述
  • 如果你的意思是var month = a.options[0,options.length].value; 那也不行
  • @Jakob 不,我的意思是数学区间[0,options.length) = {0,1,...,options.length-1}。那么,减去1就是废话了。
猜你喜欢
  • 2020-11-28
  • 2021-03-04
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2011-02-16
  • 2021-03-07
  • 1970-01-01
相关资源
最近更新 更多