创建唯一选项,然后使用 JavaScript 填充多个选择
Create unique option and then populate several selects with JavaScript
我正在用JavaScript填充几个选择。对于其中一些,选择选项是相同的,因此我考虑创建一个选项,然后填充所有相关的选择。
这是我的实际做法:
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSection.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectSection.add(option); // IE only
}
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSpecialIssue.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectSpecialIssue.add(option); // IE only
}
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectVolume.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectVolume.add(option); // IE only
}
.............ETC................
我尝试只创建一个选项(选项是相同的),然后填充这些选择:
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSection.add(option, null);
selectSpecialIssue.add(option, null);
selectVolume.add(option, null);
}
catch(ex)
{
selectSection.add(option);
selectSpecialIssue.add(option);
selectVolume.add(option);
}
这里的代码更好,更容易理解,但问题是只填充了我的最后一个选择(选择卷),我不知道为什么。
我认为
这是因为您没有启动选项对象 new。因此,您将元素附加到每个选项,但该选项只有一个对象,因此必须在另一个选择中删除它。更好的方法是在函数中执行此操作:
function setOptionJournal(selection) {
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selection.add(option, null);
}
catch(ex)
{
selection.add(option);
}
}
setOptionJournal(selectSection);
setOptionJournal(selectSpecialIssue);
setOptionJournal(selectVolume);
您可以将选项创建移动到函数
function createOption(text, value) {
var option = document.createElement('option');
option.text = text;
option.value = value == null ? 'NULL' : value;
return option;
}
并像这样编写代码
var selectSection = document.getElementById('selectSection');
var selectSpecialIssue = document.getElementById('selectSpecialIssue');
var selectVolume = document.getElementById('selectVolume');
var selectText ='please select a journal';
selectSection.add(createOption(selectText));
selectSpecialIssue.add(createOption(selectText));
selectVolume.add(createOption(selectText));
这会更干净
相关文章:
- Laravel 5.2动态下拉选择不填充(javascript)
- 单击按钮时填充javascript变量
- 使用 PHP 填充 Javascript 饼图
- 用 MySql 数据填充 JavaScript 数组
- 从代码后面填充javascript库
- 如何填充javascript数组
- 如何用随机值预填充 JavaScript 数组
- 使用 Browserify / Webpack(ES6 或 CommonJS)填充 JavaScript 资产
- 如何从 html 表数据填充 javascript 模型
- 填充 JavaScript 数组的更好方法
- 使用 PHP/MySQL 填充 JavaScript 数组
- 禁用表单字段,直到上一个字段已填充 JavaScript
- Rails + charts.js:如何使用数据库中的值填充 Javascript 数组
- 为什么 Netbeans 导航器窗格不使用特定文件名填充 JavaScript 文件
- 如何动态填充javascript函数的选项
- 用 mysql 表数据填充 Javascript OptionArray
- 从模板引擎填充javascript数组
- 如何使用SQL查询中的数据填充Javascript动态树
- 用php函数的返回值填充JavaScript变量
- 编辑自动填充javascript的设置超时