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

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

问题描述

我想使用普通的 javascript 动态地向选择添加选项.我能找到的所有内容都涉及 JQuery 或尝试动态创建选择.我能找到的最接近的东西是 动态添加带有选项的输入类型选择在 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天全站免登陆