捕捉复选框的变化和索引切换led
Catching checkbox changes and indexing to toggle LEDs
我想捕获复选框更改,并捕获选中或未选中的复选框的索引。我想知道这是否可以。
$("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返回OFF并将颜色更改为#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
在文档中必须是唯一的。当涉及到JavaScript和HTML的有效性时,这很重要。
引用:
-
:checkbox
选择器 -
addClass()
. -
closest()
. -
index()
. -
removeClass()
.
你可以这样做,如果一个复选框被选中或不使用这个在你的每个函数代码:
if ( $(this).is(':checked') ) {
// ...
} else {
// ...
}
$('input:checkbox').change(function() {
if (this.checked) {
// your code here
alert(this.value);
}
});
相关文章:
- 名称输入的索引
- 在jQuery中获取表的行索引
- 测试索引值是否等于某个数字的倍数
- 循环遍历数组中的特定索引
- 按照选项卡索引的顺序循环一个jQuery选择
- 在JavaScript中通过索引从对象数组中获取值
- 尝试在PHP中回显输入文本时出现未定义的索引错误
- 在索引.html和应用.js [node.js] 之间共享变量
- 如何为高图中的区域线创建z索引
- 下拉列表在使用z索引放置在前面后停止工作
- 减去两个索引不同但值相同的整数
- 如何通过所选索引(AngularJS)在模态弹出窗口中显示数据
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- 用javascript查询lucene索引
- 使用它更新集合中的嵌套数组's索引
- 如何将ng选项的索引作为angularJs中的值传递给模型
- Javascript获取所有锚链接的索引
- 多维关联数组的最后一个索引
- 传递给 PHP 表单时 JavaScript 动态变量上的未定义索引
- 捕捉复选框的变化和索引切换led