我想要一些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
和label
的ID
$('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" >