使用jQuery查找所选控件或文本框的标签 [英] Use jQuery to find the label for a selected control or textbox

查看:109
本文介绍了使用jQuery查找所选控件或文本框的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些jQuery代码,当我单击文本框时,它可以让我找到控件的标签...因此在HTML中,我有以下内容:

<label id="ctl00_WebFormBody_lblProductMarkup"  for="ctl00_WebFormBody_txtPriceAdjustment">This Is My Label Value</label>

<input type="text" style="width:29px;" onclick="alert('label value here');" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">

因此,当我单击我的文本框时,我想(例如)对标签内的文本进行警报...-因此,在这种情况下,它将提醒这是我的标签值"

希望如此:)

解决方案

[for='+ this.id +']一样使用属性选择器[],其中this.id是当前focus版本的 ID label

 $('input').on("focus", function() {
   var labelText = $('label[for='+  this.id  +']').text();
   console.log( labelText );  
}); 

 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="inp">This Is My Label Value</label>
<input  id="inp" type="text" > 

I want a bit of jQuery code that will allow me to find the label for a control when I click on the textbox... so in my HTML I have this:

<label id="ctl00_WebFormBody_lblProductMarkup"  for="ctl00_WebFormBody_txtPriceAdjustment">This Is My Label Value</label>

<input type="text" style="width:29px;" onclick="alert('label value here');" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">

So, when I click on my textbox, I want (for example) to do an alert... with the text that is within my label - so in this case it would alert "This is my label value"

Hope that makes sense :)

解决方案

Use the attribute selector [] like [for='+ this.id +'], where this.id is the ID of the currently focused label

$('input').on("focus", function() {
   var labelText = $('label[for='+  this.id  +']').text();
   console.log( labelText );  
});

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="inp">This Is My Label Value</label>
<input  id="inp" type="text" >

这篇关于使用jQuery查找所选控件或文本框的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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