代码之家  ›  专栏  ›  技术社区  ›  Steve Wortham

如何基于相邻字段的属性更改DOM元素的属性?

  •  1
  • Steve Wortham  · 技术社区  · 14 年前

    我正在尝试根据是否选中相邻复选框来更改标签的背景位置。

    我了解了如何使用jQuery选择相邻字段,并验证了该选择器确实有效:

    $("input[type='checkbox'] + label")
    

    这是我到目前为止得到的。。。

    $("input[type='checkbox'] + label").click(function() {
        $(this).css("background-position", $("--adjacent checkbox here--").attr('checked') ? "bottom" : "top");
    });
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   user113716    14 年前
    $("input[type='checkbox'] + label").click(function() {
        var $th = $(this);
        $th.css("background-position", $th.prev().attr('checked') ? "bottom" : "top");
    });
    

    http://api.jquery.com/prev/

    jQuery的 prev() 方法选择前一个兄弟(如果存在)。