Dar*_*ren 23 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 value here');" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">
Run Code Online (Sandbox Code Playgroud)
因此,当我点击我的文本框时,我希望(例如)使用我标签内的文本进行警告...所以在这种情况下它会提醒"这是我的标签值"
希望有道理:)
Rok*_*jan 44
使用属性选择器[]等[for='+ this.id +'],其中,this.id是所述ID的当前focus编label
$('input').on("focus", function() {
var labelText = $('label[for='+ this.id +']').text();
console.log( labelText );
});Run Code Online (Sandbox Code Playgroud)
<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" >Run Code Online (Sandbox Code Playgroud)
$("#ctl00_WebFormBody_txtPriceAdjustment").bind("click",function(){
alert($("label [for=" + this.id + "]").html());
});
Run Code Online (Sandbox Code Playgroud)
或者可能
alert($(this).closest("label").html());
Run Code Online (Sandbox Code Playgroud)
根据您的标记,您也许也可以选择下一个或上一个兄弟姐妹。