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

问题描述 投票:0回答:6
jquery jquery-selectors
6个回答
57
投票

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

$("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>


3
投票

在这样的 HTML 代码中:

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

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

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

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

或者可能

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

根据您的标记,您也许也可以选择下一个或上一个兄弟姐妹。


1
投票

试试这个:

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

0
投票
$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
  alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});

0
投票

使用 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">
© www.soinside.com 2019 - 2024. All rights reserved.