Find html label associated with a given input(查找与给定输入关联的 html 标签)
问题描述
假设我有一个 html 表单.每个 input/select/textarea 都有一个对应的 <label>
,其中 for
属性设置为它的同伴的 id.在这种情况下,我知道每个输入将只有一个标签.
Let's say I have an html form. Each input/select/textarea will have a corresponding <label>
with the for
attribute set to the id of it's companion. In this case, I know that each input will only have a single label.
在 javascript 中给定一个输入元素 —通过 onkeyup 事件,例如 —找到它的关联标签的最佳方法是什么?
Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?
推荐答案
首先,扫描页面中的标签,并从实际的表单元素中分配对标签的引用:
First, scan the page for labels, and assign a reference to the label from the actual form element:
var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}
然后,你可以简单地去:
Then, you can simply go:
document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';
不需要查找数组:)
这篇关于查找与给定输入关联的 html 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找与给定输入关联的 html 标签


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01