【问题标题】:javascript set id attribute into option not workingjavascript将id属性设置为选项不起作用
【发布时间】:2020-11-19 02:04:25
【问题描述】:

我在设置 id into 时遇到问题,在检查器中设置后我没有看到 id 属性...

第一种方式JS:

var selectorElem = document.getElementById('selector')
var optElem = document.createElement('option');
optElem.id = "750-2"
selectorElem.appendChild(optElem)
<div className="form-group">
  <select className="form-control" id="selector" />
</div>

第二种方式JS也不起作用:

var selectorElem = document.getElementById('selector')
var optElem = document.createElement('option');
optElem.setAttribute("id", "750-2")
selectorElem.appendChild(optElem)
<div className="form-group">
  <select className="form-control" id="selector" />
</div>

有什么建议吗?

【问题讨论】:

  • 我让你的代码可以运行。当我在控制台中检查它时,它们都具有它创建的选项的 ID。
  • 那么为什么我在控制台中没有 id 属性?也许是其他原因
  • 我在 Chrome 中看到了该属性。我不确定你为什么看不到它。

标签: javascript html reactjs select


【解决方案1】:

setAttribute 对我有用

var optElem = document.createElement('option');
optElem.setAttribute('id', '750-2')
console.log(optElem.id) //Output -> "750-2"

【讨论】:

    猜你喜欢
    • 2011-10-28
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2014-08-23
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多