页面中无法识别JS方法

时间:2018-09-09 23:12:24

标签: javascript methods

我正在尝试创建一个简单的js脚本,该脚本会动态填充2个下拉列表,但我不知道我的脚本在做什么错:(

<head>
    <script>
        var carModels = {
            Audi : ["A3", "A4" ],
            Alfa-Romeo : ["Giullietta", "Giullia" ]
        }

        function makeSubmenu(value) {
            if (value.length == 0){
                document.getElementById("modelId").innerHTML = "<option></option>";
            } else {
                var modelOptions = "";
                for (modelCar in carModels[value]) {
                    modelOptions += "<option>" + carModels[value][modelCar]
                            + "</option>";
                }
                document.getElementById("modelId").innerHTML = modelOptions;
            }
        }

        function resetSelection() {
            document.getElementById("marcaId").selectedIndex = 0;
            document.getElementById("modelId").selectedIndex = 0;
        }
    </script>
</head>
<body onload="resetSelection()">
<div align="center">
    <form th:action="@{/search}" method="POST">

        <select id="marcaId" size="1" name="marca" required onchange="makeSubmenu(this.value)">
            <option></option>
            <option>Audi</option>
            <option>Alfa-Romeo</option>
        </select>

        <select id="modelId" size="1" name="model" required >
            <option></option>
        </select>

        <input type="submit" value="Search">
    </form>
 </body>

我得到了这两个错误:

Uncaught ReferenceError: resetSelection is not defined
    at onload ((index):6)
Uncaught ReferenceError: makeSubmenu is not defined
    at HTMLSelectElement.onchange ((index):13)
onchange @ (index):13

我不明白为什么它说那些方法没有定义

1 个答案:

答案 0 :(得分:2)

您需要将属性Alfa-Romeo用引号引起来,例如..

var carModels = {
    Audi : ["A3", "A4" ],
    "Alfa-Romeo" : ["Giullietta", "Giullia" ]
}

请参考this answer进行推理。

  

引用对象键的唯一原因是

     
      
  • 属性名称由浏览器/ js引擎保留/使用(例如,   IE中的“类”
  •   
  • 键中有特殊字符或空格
  •