将javascript数组插入HTML表单

时间:2018-03-25 12:02:58

标签: javascript html arrays forms dropdown

我对js完全不熟悉,我对Python有点了解,但我很困惑将JS与HTML结合起来。

我正在尝试将数组转换为HTML下拉列表,但我似乎无法让它工作。

    

<HEAD>
    <TITLE>Exercise Arrays</TITLE>
</HEAD>

<BODY>
    <script>
        var city;
        var userInput = [];
        while (city !== "stop") {
            city = prompt('Please enter a city or type: "stop" to end');
            if (city === "stop") {
                break;
            }
            else {
                userInput.push(city)
            }
        }
        document.write("<h1>Exercise arrays </h1>")
        document.write("<h2> States: </h2>")
        document.write("<form><select>" + city + "</select></form>")
    </script>

    </table>
</BODY>

</HTML>

1 个答案:

答案 0 :(得分:0)

循环列表并将option元素添加到您的下拉列表中。我将静态部分重新构建为HTML,并通过其select访问id

var city;
var userInput = [];
while (true) {
    city = prompt('Please enter a city or type: "stop" to end');
    if (city === "stop") {
        break;
    }
    else {
        userInput.push(city)
    }
}

// For each item referred to as `city`, add an option
userInput.forEach(city => dropdown.add(new Option(city)));
<h1>Exercise arrays</h1>
<h2> States: </h2>
<select id="dropdown"></select>