如何在vanilla javascript中动态添加选项到现有选择 [英] how to dynamically add options to an existing select in vanilla javascript

查看:300
本文介绍了如何在vanilla javascript中动态添加选项到现有选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用普通的javascript动态添加选项。我能找到的一切都涉及JQuery或尝试动态创建选择。我能找到的最接近的是动态添加输入类型select with options在Javascript 中执行后者并且是我发现的唯一不涉及JQuery的。虽然我确实尝试过这样使用它:

I'd like to add option to a select dynamically using plain javascript. Everything I could find involves JQuery or tries to create the select dynamically as well. The closest thing I could find was Dynamically add input type select with options in Javascript which does the latter and was the only I found that doesn't involve JQuery. Although I did try and use it like so:

daySelect = document.getElementById('daySelect');
daySelect.innerHTML += "<option'>Hello world</option'>";
alert(daySelect.innerHTML)

在我这样做后,选择没有变化警报给了我

After I did this there was no change to the select and the alert gave me

HELLO WORLD</option'>

如果这很简单,我很抱歉,但我对javascript和网络编程很新。感谢您的帮助。

I apologize if this is simple but I'm very new at javascript and web programming in general. Thank you for any assistance.

编辑:所以我尝试了这样的建议。

So I tried the given suggestions like so.

daySelect = document.getElementById('daySelect');
myOption = document.createElement("option");
myOption.text = "Hello World";
myOption.value = "Hello World";
daySelect.appendChild(myOption);

这根本没有改变页面中的选择。知道为什么吗?我确实检查了代码是否正在运行警报。

This has not changed the select in the page at all. Any idea why? And I did check that the code was being run with an alert.

编辑:这个想法确实有效,它只是证明它没有显示一个值落下。我不知道为什么,但我可以想出那一个。

The idea did work, it just turned out that it wasn't displaying a value in the dropdown. I don't know why but I can figure that one out I think.

推荐答案

本教程准确显示了你需要做什么:使用javascript 向HTML选择框添加选项

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript

基本上:

 daySelect = document.getElementById('daySelect');
 daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');

这篇关于如何在vanilla javascript中动态添加选项到现有选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆