htmlFor not working(htmlFor 不工作)
问题描述
我使用 JavaScript 为每个按钮创建了 3 个 radio
按钮和一个 label
.当我尝试使用 htmlFor
在标签中添加 for
时,它不会将其应用于实际的 DOM 元素.意思是,当我尝试在网页上使用 label
时,它不会选择 radio
按钮.
I created 3 radio
buttons and a label
for each of them using JavaScript. When I try adding for
in the label using htmlFor
, it doesn't apply it to the actual DOM Element. Meaning, when I try using the label
on the webpage, it doesn't select the radio
button.
我检查了开发人员工具,发现 labels
没有应用 for
.
I checked in the developer tools, and saw that the labels
did not have for
applied to them.
我做错了什么,我该如何解决?
What am I doing wrong, and how can I fix it?
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
).
The htmlFor
is used to bind a label to a specific form element. However, it uses the id
of that form element (not the name
).
来源MDN:
HTMLLabelElement.htmlFor 属性反映了 for 的值内容属性.这意味着这个脚本可访问的属性是用于设置和读取 的 content 属性的值,即标签关联控件元素的 ID.
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.
另外,在你的小提琴中,你拼错了 label
.
Also, in your fiddle, you misspelled label
.
更新小提琴:https://jsfiddle.net/h09mm827/2/
这篇关于htmlFor 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:htmlFor 不工作


基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01