html不工作

htmlFor not working

我使用 JavaScript 创建了 3 个 radio 按钮和每个按钮的 label。当我尝试使用 htmlFor 在标签中添加 for 时,它不会将其应用于实际的 DOM 元素。意思是,当我尝试在网页上使用 label 时,它不会 select radio 按钮。

我查看了开发者工具,发现 labels 没有应用 for

我做错了什么,我该如何解决?

JSFiddle

var _doc = document,
  sliderWrapper = _doc.getElementById('sliderWrapper'),
  radioWrapper = _doc.createElement('div');

for (var i = 0; i < 3; i++) {
  var radio = _doc.createElement('input');
  var niceRadio = _doc.createElement('lable');
  var index = radioWrapper.children.length / 2;

  niceRadio.className = 'niceRadio';
  niceRadio.htmlFor = radio.id = 'sliderRadio' + index;
  radio.type = 'radio';
  radio.name = 'myName';

  radioWrapper.appendChild(radio);
  radioWrapper.appendChild(niceRadio);
  console.log(niceRadio.htmlFor);
}

sliderWrapper.appendChild(radioWrapper);
.niceRadio {
  position: relative;
  width: 20px;
  height: 20px;
  cursor: pointer;
  border-radius: 50%;
  border: 5px solid orange;
}
.niceRadio:hover {
  border-color: lightblue;
}
<div id="sliderWrapper">
</div>

htmlFor 用于将标签绑定到特定的表单元素。但是,它使用该表单元素的 id(而不是 name)。

来源MDN:

The HTMLLabelElement.htmlFor property reflects the value of the for content property. That means that this script-accessible property is used to set and read the value of the content property for, which is the ID of the label's associated control element.

此外,在您的 fiddle 中,您拼错了 label

已更新 fiddle:https://jsfiddle.net/h09mm827/2/