【问题标题】:jQuery change only certain index of a checkbox name arrayjQuery仅更改复选框名称数组的某些索引
【发布时间】:2017-01-31 08:44:09
【问题描述】:

我有一个复选框数组和一个选中/取消选中所有功能。当我取消选中所有时,我想确保第一个仍然被选中,但它不能按以下方式工作:

$("input[name='temps[]']").removeAttr("checked");   // works
$("input[name='temps[0]']").prop("checked", true);  // doesn't work

是否有一种解决方法,这样我就不必在循环生成复选框中使用它,否则我无法做到这一点,例如给第一个复选框一个 id?

$("#firstBox").prop("checked", true) 

【问题讨论】:

  • 也许使用 first-child 选择器?
  • 您能否发布您的完整代码以便更好地理解?
  • 使用这个$('input[name="temp[]"]:first').prop('checked',true);

标签: jquery checkboxlist


【解决方案1】:

您可以使用.eq(index ):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);

【讨论】:

  • 这个 .eq() 是完美的解决方案。我赞成所有答案,但它不会显示。
  • 哦,我明白了!我会弥补的。
【解决方案2】:

查看您的 HTML 源代码。元素名称是 temps[] 而不是 temps[0]。这就是为什么第二个选择器不起作用的原因。

要先选择,请使用.eq(0):

$("input[name='temps[]']")
    .removeAttr("checked")
    .eq(0)
    .addClass('checked')
    .prop('checked', true)
;

【讨论】:

    【解决方案3】:

    您可以使用eq() 函数从jQuery 列表中按编号提取项目。这将创建一个仅包含该项目的派生列表,然后您可以照常进行:

    $("input[name='temps[]']").eq(0).prop("checked", true);
    

    【讨论】:

      【解决方案4】:
      $("input[name='temps[]']")[0].prop("checked", true);
      

      或者

      $("input[name='temps[]:first']").prop("checked", true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 2013-08-29
        • 2022-01-20
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多