【发布时间】:2022-06-15 05:52:17
【问题描述】:
我正在尝试更改使用 js 函数 createElement() 创建的 select html 元素的选定值,但由于某种原因,即使我更改了选定索引,它也保持不变。代码如下:
let vendor_cell = document.createElement("td");
let vendor_dropdown = document.createElement("select");
vendor_dropdown.setAttribute("id", "selectID" );
for (let vendorID in vendors) { //generates options using vendors array.
let option = document.createElement("option");
option.value = vendorID;
option.text = vendors[vendorID];
vendor_dropdown.add(option);
}
document.getElementById("selectID").selectedIndex = "3";
vendor_cell.appendChild(vendor_dropdown)
row.appendChild(vendor_cell);
【问题讨论】:
-
为什么将 selectedIndex 设置为“3”而不是 3?
-
我只是在尝试不同的方法,看看它是否可行。我原来是3的,还是不行。
-
在尝试使用
getElementById查找之前,您是否还没有真正将您创建的元素添加到 DOM 中?你找不到什么还没有。 -
我已经尝试将 getElementById 行放在我的表生成函数中,包括最后,但这仍然没有改变任何东西。该表包含此选择元素作为单元格。
-
你试过
vendor_dropdown.selectedIndex = 3;吗?
标签: javascript