使用jQuery查找所选控件或文本框的标签
我想要一点jQuery代码,当我点击文本框时,它可以让我找到控件的标签。。。因此,在我的HTML中,我有以下内容:使用jQuery查找所选控件或文本框的标签,jquery,jquery-selectors,Jquery,Jquery Selectors,我想要一点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 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">
这是我的标签值
所以,当我点击我的文本框,我想(例如)做一个警报。。。与我的标签中的文本-因此在本例中,它将发出警报“这是我的标签值”
希望这是有道理的:)
或者可能
alert($(this).closest("label").html());
根据您的标记,您也可以选择下一个或上一个同级 在这样的HTML代码中:
<label for="input-email">Email</label>
<input type="text" name="input-email" value="" />
试试这个:
$('input[type=text]').focus(function(){
alert($('label[for=' + $(this).attr('id') + ']').html());
});
使用属性选择器
[]
就像[for='+this.id+']
一样,其中this.id
是当前焦点ed标签的id
$('input')。在(“焦点”,函数()上){
var labelText=$('label[for='+this.id+']')。text();
控制台日志(labelText);
});代码>
这是我的标签值
使用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">
函数displayMessage()
{
警报(document.getElementById(“ctl00\u WebFormBody\u lblProductMarkup”).innerHTML);
}
这是我的标签值
Id使用此选项,但看起来您使用的是asp.net web表单,因此请使用实际控件的clientID:$('')。单击(function(){…等)。这将使您的代码在获取呈现控件Id方面更加健壮。标签上的属性应与输入上的Id属性相对应。
$('input[type=text]').focus(function(){
alert($('label[for=' + $(this).attr('id') + ']').html());
});
$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});
<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">