像
[]
一样使用属性选择器[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>
在这样的 HTML 代码中:
<label for="input-email">Email</label>
<input type="text" name="input-email" value="" />
你可以找到这样的标签内容:
$('label[for="input-email"]').html();
$("#ctl00_WebFormBody_txtPriceAdjustment").bind("click",function(){
alert($("label [for=" + this.id + "]").html());
});
或者可能
alert($(this).closest("label").html());
根据您的标记,您也许也可以选择下一个或上一个兄弟姐妹。
试试这个:
$('input[type=text]').focus(function(){
alert($('label[for=' + $(this).attr('id') + ']').html());
});
$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});
使用 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">