2009-07-27 65 views
212
<input type="checkbox" name="filter" id="comedyclubs"/> 
<label for="comedyclubs">Comedy Clubs</label> 

如果我有一個複選框與描述它的標籤,我怎樣才能使用jQuery選擇標籤?給標籤標籤一個ID並使用$(#labelId)選擇該標籤會更容易嗎?jQuery選擇器的複選框的標籤

回答

386

這應該工作:

$("label[for='comedyclubs']") 

參見:Selectors/attributeEquals - jQuery JavaScript Library

+3

對於WebKit瀏覽器(Safari /鉻),你可以做`$( '#comedyclubs')[0] .labels`訪問指定`#comedyclubs`的所有標籤。 – Matt 2012-08-09 02:17:08

+1

使用.text()將對象轉換爲字符串: alert($(「label [for ='comedyclubs']」)。text()); – Loren 2012-12-12 18:56:35

+0

只需使用$(「label [for ='comedyclubs']」)即可獲得價值,但會使標籤變爲空白。所以,使用$(「label [for ='comedyclubs']」)。text() – shahil 2014-01-12 08:47:33

40

這應做到:

$("label[for=comedyclubs]") 

如果有非字母數字字符您的帳號,那麼你必須圍繞ATTR報價值:

$("label[for='comedy-clubs']") 
+2

奇怪的是,當這個答案被提交的時間和領先的答案一樣時,聲譽如何。 :) – sscirrus 2013-04-19 05:56:39

5

另一種解決辦法是:

$("#comedyclubs").next() 
60
$("label[for='"+$(this).attr("id")+"']"); 

這應該允許您在一個循環中的所有字段選擇標籤爲好。所有你需要確保的是你的標籤應該說for='FIELD'其中FIELD是這個標籤被定義的字段的id。

0

感謝硤,對於那些誰可能會尋找到實現使用$相同(本),而迭代或函數內的關聯:

$("label[for="+$(this).attr("id")+"]").addClass("orienSel"); 

我看了一會兒,而工作的這個項目,但不能找到一個很好的例子,所以我希望這可以幫助其他可能希望解決相同問題的人。

在上面的示例中,我的目標是隱藏無線電輸入並設置標籤樣式以提供更加流暢的用戶體驗(更改流程圖的方向)。

您可以see an example here

如果你喜歡的例子,這裏是CSS:

.orientation {  position: absolute; top: -9999px; left: -9999px;} 
    .orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;} 
    .orR{ background-position: 9px -57px;} 
    .orT{ background-position: 2px -120px;} 
    .orB{ background-position: 6px -177px;} 

    .orienSel {background-color:#323232;} 

和JavaScript相關的部分:

function changeHandler() { 
    $(".orienSel").removeClass("orienSel"); 
    if(this.checked) { 
     $("label[for="+$(this).attr("id")+"]").addClass("orienSel"); 
    } 
}; 

的備用根原問題,考慮到標籤跟隨輸入,你可以去一個純CSS的解決方案,並避免使用JavaScript ...

input[type=checkbox]:checked+label {}