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 标签
基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01