查找与给定输入关联的 html 标签 [英] Find html label associated with a given input

查看:20
本文介绍了查找与给定输入关联的 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 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆