【问题标题】:Change the selectedindex of a select element generated using js not working更改使用 js 生成的选择元素的 selectedindex 不起作用
【发布时间】: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


【解决方案1】:

你会试试吗?

const 
  row             = document.querySelector('table tr')
, vendor_dropdown = row.insertCell().appendChild( document.createElement('select') )
  ;
var vendors = 
  { '1': 'Acer'
  , '2': 'HP'
  , '3': 'MARCONI INSTR'
  , '4': 'ALESSI IND'     // --> index value is 3
  } 

Object.entries(vendors).forEach(([key,val], i) =>
  { 
  vendor_dropdown.add(new Option(val,key,(i===3),(i===3)))
  })
<table>
  <tr>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2012-09-18
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多