创建唯一选项,然后使用 JavaScript 填充多个选择

Create unique option and then populate several selects with JavaScript

本文关键字:填充 JavaScript 选择 唯一 选项 然后 创建      更新时间:2023-09-26

我正在用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));

这会更干净