jQuery 仅更改复选框名称数组的特定索引
jQuery change only certain index of a checkbox name array
我有一个复选框数组和一个 checkall/uncheck all 函数。当我全部取消选中时,我想确保第一个保持选中状态,但它无法按以下方式工作:
$("input[name='temps[]']").removeAttr("checked"); // works
$("input[name='temps[0]']").prop("checked", true); // doesn't work
是否有解决方法,这样我就不必在生成复选框的循环中麻烦它,或者没有例如我无法做到这一点给第一个复选框一个 ID?
$("#firstBox").prop("checked", true)
您可以使用.eq(index )
or :eq(index )
获取指定索引处的元素,然后执行所需的操作
$("input[name='temps[]']").eq(index).prop("checked", true);
或者,
$("input[name='temps[]']:eq(" + index + ")").prop("checked", true);
您还可以使用 :first
selector 获取第一个匹配的 DOM 元素
$("input[name='temps[]:first']").prop("checked", true);
查看您的 HTML 来源。元素名称是 temps[]
而不是 temps[0]
。这就是为什么第二个 selector 不起作用。
到select先用.eq(0)
:
$("input[name='temps[]']")
.removeAttr("checked")
.eq(0)
.addClass('checked')
.prop('checked', true)
;
您可以使用 eq()
函数从 jQuery 列表中按编号提取项目。这将创建一个仅包含该项目的派生列表,然后您可以照常进行:
$("input[name='temps[]']").eq(0).prop("checked", true);
$("input[name='temps[]']")[0].prop("checked", true);
或者
$("input[name='temps[]:first']").prop("checked", true);
我有一个复选框数组和一个 checkall/uncheck all 函数。当我全部取消选中时,我想确保第一个保持选中状态,但它无法按以下方式工作:
$("input[name='temps[]']").removeAttr("checked"); // works
$("input[name='temps[0]']").prop("checked", true); // doesn't work
是否有解决方法,这样我就不必在生成复选框的循环中麻烦它,或者没有例如我无法做到这一点给第一个复选框一个 ID?
$("#firstBox").prop("checked", true)
您可以使用.eq(index )
or :eq(index )
获取指定索引处的元素,然后执行所需的操作
$("input[name='temps[]']").eq(index).prop("checked", true);
或者,
$("input[name='temps[]']:eq(" + index + ")").prop("checked", true);
您还可以使用 :first
selector 获取第一个匹配的 DOM 元素
$("input[name='temps[]:first']").prop("checked", true);
查看您的 HTML 来源。元素名称是 temps[]
而不是 temps[0]
。这就是为什么第二个 selector 不起作用。
到select先用.eq(0)
:
$("input[name='temps[]']")
.removeAttr("checked")
.eq(0)
.addClass('checked')
.prop('checked', true)
;
您可以使用 eq()
函数从 jQuery 列表中按编号提取项目。这将创建一个仅包含该项目的派生列表,然后您可以照常进行:
$("input[name='temps[]']").eq(0).prop("checked", true);
$("input[name='temps[]']")[0].prop("checked", true);
或者
$("input[name='temps[]:first']").prop("checked", true);