我有以下HTML:
const span = document.getElementById("userdropdownlist");
console.log(span);
<select>
<span id="userdropdownlist"></span><br>
</select>
当我尝试将document.getElementById
与上面的span
ID一起使用时,出现错误消息
“未捕获的TypeError:无法读取null的属性'innerHTML'”。
在我看来,javascript无法在span
标记内看到select
个ID。
如何解决这个问题?
答案 0 :(得分:2)
选择不能包含<span>
元素,选择只能包含<option>
答案 1 :(得分:0)
如上所述,将<option>
以外的任何内容作为<select>
的子元素放置都是无效的HTML。以下演示功能具有options()
功能。目的是根据给定的Map对象将选项添加到给定的select中。 Map对象存储每个选项的值和文本内容。
详细信息在演示中进行了评论。
/*[REQUIRED]
Prepare a Map Object as the first parameter
Each sub-array is an option [value, text]
These key/value pairs/sub-arrays are nested within another array
then passed to the Map()
*/
let kvp = new Map([
['Alpha', 'α'],
['Beta', 'β'],
['Gamma', 'γ'],
['Delta', 'δ'],
['Epsilon', 'ε'],
['Zeta', 'ζ']
]);
/*[REQUIRED]
First param is the Map previously mentioned
Second param is a selector string of the select receiving options
-A- Reference the select
-B- Iterate thru the map -- destructure the key/value to access
-C- Create an option
-D- Get val from map and set it to option value
-E- Get txt from map and set it to option text
-F- Add to select
*/
const options = (map, select) => {
const sel = document.querySelector(select); //A
for (let [val, txt] of map) { //B
let opt = document.createElement('option'); //C
opt.value = val; //D
opt.text = txt; //E
sel.add(opt); //F
}
}
// Call options() pass kvp Map and selector String
options(kvp, '.sel');
/* [OPTIONAL]
When change event happens on select.sel output.out displays select.sel value
*/
document.querySelector('.sel').onchange = function(e) {
document.querySelector('.out').value = this.value;
}
select,
output {
display: inline-block;
font: 700 64px/1.2 Consolas
}
<select class='sel'></select>
<output class='out'></output>