简体   繁体   English

html对于不起作用

[英]htmlFor not working

I created 3 radio buttons and a label for each of them using JavaScript. 我使用JavaScript创建了3个radio按钮和一个label When I try adding for in the label using htmlFor , it doesn't apply it to the actual DOM Element. 当我尝试添加for在使用标签htmlFor ,它并不将其应用到实际的DOM元素。 Meaning, when I try using the label on the webpage, it doesn't select the radio button. 意思是,当我尝试使用网页上的label时,它没有选择radio按钮。

I checked in the developer tools, and saw that the labels did not have for applied to them. 我在开发者工具检查,看到该labels没有for适用于他们。

What am I doing wrong, and how can I fix it? 我在做什么错,该如何解决?

JSFiddle 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> 

The htmlFor is used to bind a label to a specific form element. htmlFor用于将标签绑定到特定的表单元素。 However, it uses the id of that form element (not the name ). 但是,它使用该表单元素的id (而不是name )。

Source MDN : 来源MDN

The HTMLLabelElement.htmlFor property reflects the value of the for content property. HTMLLabelElement.htmlFor属性反映了for content属性的值。 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. 这意味着该脚本可访问的属性用于设置和读取content属性的值,该属性标签关联的控件元素的ID

Also, in your fiddle, you misspelled label . 另外,在您的小提琴中,您拼写了label

Updated fiddle: https://jsfiddle.net/h09mm827/2/ 更新小提琴: https : //jsfiddle.net/h09mm827/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM