查找与给定输入关联的 html 标签

2022-01-25 00:00:00 label javascript 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!';

不需要查找数组:)

相关文章