代码之家  ›  专栏  ›  技术社区  ›  Darwyn

复选框标签的jQuery选择器

  •  223
  • Darwyn  · 技术社区  · 15 年前
    <input type="checkbox" name="filter" id="comedyclubs"/>
    <label for="comedyclubs">Comedy Clubs</label>
    

    如果我有一个带有描述它的标签的复选框,如何使用jquery选择标签?给标签标签一个ID,然后使用 $(#labelId) ?

    5 回复  |  直到 8 年前
        1
  •  411
  •   Kip    15 年前

    这应该有效:

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

    参见: Selectors/attributeEquals - jQuery JavaScript Library

        2
  •  65
  •   gsamaras a Data Head    9 年前
    $("label[for='"+$(this).attr("id")+"']");
    

    这应该允许您为循环中的所有字段选择标签。你只需要确保你的标签上写着 for='FIELD' 哪里 FIELD 为其定义此标签的字段的ID。

        3
  •  42
  •   Darko    15 年前

    应该这样做:

    $("label[for=comedyclubs]")
    

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

    $("label[for='comedy-clubs']")
    
        4
  •  5
  •   BCsongor    14 年前

    另一种解决方案可能是:

    $("#comedyclubs").next()
    
        5
  •  0
  •   Pete - iCalculator    8 年前

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

    $("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 {}