javascript - 捕获复选框更改并索引以切换 LED

标签 javascript jquery checkbox

我想捕获复选框更改,并捕获选中或未选中的复选框的索引。我想知道这是否可以。

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

我的 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>

所以我想检测选择了哪个框,然后将 LED 更改为 ON 并更改为红色背景颜色。另一方面,如果未选择该框,我想将 LED 返回为关闭并将颜色更改为 #cccccc

最佳答案

没有更多详细信息,这是我可以提供的最通用的代码(更多信息会带来很好的答案):

$('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
        }
});

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

$('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';
    });
});

JS Fiddle demo .

将上面的 jQuery 与以下 CSS 结合起来:

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

.led.on {
    color: #000;
    background-color: #f00;
}

和 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>

请注意,我已将 id="led" 替换为 class="led",因为 id < em>在文档中必须是唯一的。当涉及到 JavaScript 和 HTML 有效性时,这一点很重要。

引用文献:

关于javascript - 捕获复选框更改并索引以切换 LED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15851894/

相关文章:

javascript - 使用 promises 从 mongo db 检索对象时出错

javascript - 为什么在 Javascript 中 `x === x++` 为真而 `x++ === x` 为假?

javascript - JS : How to detect if location is disabled on a mobile device?

javascript - 如何在元素的原始文本之前添加文本

java - Android Eclipse findViewByID 与以编程方式 CheckBox

jquery - 根据唯一选择或不同的复选框组合(例如超过 2 个)显示内容

php - javascript 中的 file_Get_contents

javascript - div出现在鼠标坐标上

javascript - 元素事件监听器上的 this.id 成为单击元素的所有 id 的数组

jquery - 分组复选框并允许在每组中最多检查三个