2011-09-17 47 views
19

我想要一點jQuery代碼,當我單擊文本框時,將允許我找到控件的標籤...所以在我的HTML中我有這樣的代碼:使用jQuery爲所選控件或文本框查找標籤

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

所以,當我點擊我的文本框,我希望(例如)做的警報......與我的標籤中的文本 - 所以在這種情況下,它會提醒「這是我的標籤值」

希望是有道理的:)

回答

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

或可能

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

取決於你的標記,你可能只是能夠選擇下一首或上的兄弟姐妹了。

2

在HTML代碼像這樣的:

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

您可以找到標籤內容是這樣的:

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

的用於在標籤標記屬性應該對應於ID屬性上輸入。 –

1

試試這個:

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

使用屬性選擇[][for='+ this.id +'],其中this.idID當前focus ED的label

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

+2

身份證去與這一個,但它看起來像你使用的是asp.net網頁形式,所以使用你的實際控制的客戶端ID:$('<%= txtPriceAdjustment.ClientID%>')。click(function(){...等等。這將使您的代碼在獲取呈現的控件ID方面更加健壯 –

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"> 
相關問題