使用jQuery查找所选控件或文本框的标签

wlzqhblo  于 12个月前  发布在  jQuery
关注(0)|答案(6)|浏览(115)

我想要的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">

所以,当我点击我的文本框,我想(例如)做一个警报.与我的标签内的文本-所以在这种情况下,它会警告“这是我的标签值”
希望有意义:)

vmpqdwk3

vmpqdwk31#

使用属性选择器[],如'[for="'+ this.id +'"]',其中this.id是当前focus艾德labelID

$("input").on("focus", function() {
   const labelText = $('label[for="'+ this.id +'"]').text();
   console.log( labelText );  
});
<label for="inp">This Is My Label Value</label>
<input  id="inp" type="text">

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

fkvaft9z2#

在这样的HTML代码中:

<label for="input-email">Email</label>
<input type="text" name="input-email" value="" />

你可以找到这样的标签内容:

$('label[for="input-email"]').html();
x4shl7ld

x4shl7ld3#

$("#ctl00_WebFormBody_txtPriceAdjustment").bind("click",function(){
    alert($("label [for=" + this.id + "]").html());
});

或可能

alert($(this).closest("label").html());

根据你的标记,你也可以选择下一个或上一个兄弟。

rfbsl7qr

rfbsl7qr4#

试试这个:

$('input[type=text]').focus(function(){
     alert($('label[for=' + $(this).attr('id') + ']').html());
});
57hvy0tb

57hvy0tb5#

$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
  alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});
e5nqia27

e5nqia276#

用JavaScript来做

<script type="text/javascript">
function displayMessage()
{
alert(document.getElementById("ctl00_WebFormBody_lblProductMarkup").innerHTML);
}
</script>

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

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

相关问题