Uncaught TypeError: sel.add is not a function

Uncaught TypeError: sel.add is not a function

  1. HTML 带有 select 标签:

    <select id="sel"></select>`
    
  2. 在 JavaScript 部分,我试图在 select 下拉列表中添加选项,在循环中创建它们,将数组值分配给选项:

    var sel = document.getElementById('sel').value;
    var jsonobj = {School_charles: {class_A: [{ idkey: "1", name: "john" },
                  { idkey: "2", name: "jill" }]}};
    
    for(var i = 0; i <= jsonobj.School_charles.class_A.length; i++) {
        var option = document.createElement('option');
        option.text = jsonobj.School_charles.class_A[i].idkey;
        option.value = jsonobj.School_charles.class_A[i].name;
        sel.add(option);    
    }
    

请告诉我哪里错了,我正在学习JavaScript。

你的代码有两个错误:

  1. var sel = document.getElementById('sel').value; 应该只是 var sel = document.getElementById('sel'); 所以变量 sel 引用实际的 select 元素而不是 select 值。这就是 add() 方法未被识别的原因。
  2. 你的 for 循环条件应该只是 i < jsonobj.School_charles.class_A.length 而不是 <=

var sel = document.getElementById('sel');
var jsonobj = {
  School_charles: {
    class_A: [{
      idkey: "1",
      name: "john"
    }, {
      idkey: "2",
      name: "jill"
    }]
  }
};

for (var i = 0; i < jsonobj.School_charles.class_A.length; i++) {
  var option = document.createElement('option');
  option.text = jsonobj.School_charles.class_A[i].idkey;
  option.value = jsonobj.School_charles.class_A[i].name;
  sel.add(option);
}
<select id="sel"></select>

那里有两个错误

  • document.getElementById('sel').value 应该是 document.getElementById('sel')
  • i <= jsonobj.School_charles.class_A.length 应该是 i < jsonobj.School_charles.class_A.length

var sel = document.getElementById('sel');
var jsonobj = {School_charles: {class_A: [{ idkey: "1", name: "john" },
              { idkey: "2", name: "jill" }]}};

for(var i = 0; i < jsonobj.School_charles.class_A.length; i++) {
    var option = document.createElement('option');
    option.text = jsonobj.School_charles.class_A[i].idkey;
    option.value = jsonobj.School_charles.class_A[i].name;
    sel.add(option);    
}
<select id="sel"></select>