用于复选框标签的jQuery选择器

时间:2009-07-27 04:21:25

标签: jquery checkbox jquery-selectors

<input type="checkbox" name="filter" id="comedyclubs"/>
<label for="comedyclubs">Comedy Clubs</label>

如果我有一个带有描述它的标签的复选框,我该如何使用jQuery选择标签?为标签标签提供ID并使用$(#labelId)选择该标识会更容易吗?

5 个答案:

答案 0 :(得分:418)

这应该有效:

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

另请参阅:Selectors/attributeEquals - jQuery JavaScript Library

答案 1 :(得分:67)

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

这应该允许您为循环中的所有字段选择标签。您需要确保的是标签应该是for='FIELD',其中FIELD是要为其定义此标签的字段的ID。

答案 2 :(得分:43)

这应该这样做:

$("label[for=comedyclubs]")

如果您的ID中包含非字母数字字符,则必须用引号括住attr值:

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

答案 3 :(得分:5)

另一种解决方案可能是:

$("#comedyclubs").next()

答案 4 :(得分:0)

感谢Kip,对于那些可能希望在函数内迭代或关联时使用$(this)实现相同目标的人:

<ul>
  <li><a href="javascript:openNav();" id=""  >Menu</a></li>
</ul>

我在这个项目工作期间找了一段时间但是找不到一个很好的例子,所以我希望这可以帮助那些可能想要解决同一问题的人。

在上面的示例中,我的目标是隐藏无线电输入并设置标签样式以提供更流畅的用户体验(更改流程图的方向)。

你可以see an example here

如果你喜欢这个例子,这里是css:

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

以及JavaScript的相关部分:

.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;}

原始问题的备用根,如果标签在输入后面,你可以使用纯css解决方案并避免完全使用JavaScript ......:

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