捕捉复选框更改和索引以切换LED

ele*_*ixG 2 javascript checkbox jquery

我想抓住一个复选框更改,同时捕获已选中或未选中复选框的索引.我想知道这是否可以.

$("input[type='checkbox']").change(function () {
  $("input[type='checkbox']").each(function (i) {
    //my code here
    switch (i) {
      case 0:
        break;
      case 1:
        break;
          .
          .
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

我的HTML是这样的:

<table>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
</table>
Run Code Online (Sandbox Code Playgroud)

因此,我想检测选择了哪个框,然后将LED更改为ON和红色背景颜色.另一方面,如果未选中该框,我想将LED返回OFF并将颜色更改为#cccccc

Dav*_*mas 5

没有进一步的细节,这是我能提供的最通用的代码(更多信息来得很好,呃,答案):

$('input:checkbox').change(function(){
    // caching the $(this) jQuery object, since we're using it more than once:
    var that = $(this),
         // index of element with regard to its sibling elements:
        index = that.index(),
        // index with regard to other checkbox elements:
        checkboxIndex = that.index('input:checkbox');

        if (this.checked){ // this.checked evaluates to a Boolean (true/false)
            // this block executed only if the checkbox *is* checked
        } else {
            // this block executed only if the checkbox is *not* checked
        }
});
Run Code Online (Sandbox Code Playgroud)

编辑以解决(编辑/澄清)问题中的要求:

$('input:checkbox').change(function () {
    var that = this,
        $that = $(that),
        led = $that.closest('tr').find('td:first-child');
    led.removeClass('on off').addClass(function(){
        return that.checked ? 'on' : 'off';
    });
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

将上面的jQuery与以下CSS结合使用:

.led,
.led.off {
    background-color: #ccc;
}

.led.on {
    color: #000;
    background-color: #f00;
}
Run Code Online (Sandbox Code Playgroud)

和HTML:

<table>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

请注意,我已经替换了id="led"wtih class="led",因为id 文档中必须是唯一的.当谈到JavaScript和HTML有效性时,这很重要.

参考文献:

  • 我在哪里创建全局变量?所有变量都遵循本地范围内的`var`声明.还是我错过/误解了什么?我不喜欢使用`that.is(':checked')`和`that.prop('checked')`,只是因为它不必要地昂贵(即使我没有缓存`this`节点). (2认同)