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 标签


基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01