我正在使用 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);
}
这里的代码更好,更容易理解,但问题是只有我的最后一个选择(selectVolume)被填充,我不知道为什么。
最佳答案
我认为这是因为你没有初始化选项对象新。因此,您将元素附加到每个选择,但该选项只有一个对象,因此必须在另一选择中将其删除。更好的方法是在函数内执行此操作:
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);
关于javascript - 创建唯一选项,然后使用 JavaScript 填充多个选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11858802/