访问 HTML 上的数组键复选框

Accessing key of an array on HTML check boxes

本文关键字:复选框 数组 HTML 访问      更新时间:2023-09-26

>我有一个带有复选框的树,他们的ID有项目键和值作为他们的值。

<input type="checkbox" name="list_code[4]" id="list_code[4]" value="AG12345678" checked="checked">

当用户选择树元素时,我可以通过以下方法访问它们

$('input[name^="list_code"]').each(function() {
    if ($(this).attr('checked')) 
        list_code = $(this).val();
});

我能够AG12345678获得值,但我也需要获取键值,在这种情况下,这是从 list_code[4] 4的。如何访问该值?

var n = this.id.slice(this.id.indexOf('[') + 1, this.id.indexOf(']'));

或。。。

var n = this.id.replace(/'D/g, '');

或。。。

var n = (this.id.match(/'d+/) || [])[0];

或者如果可能有其他不需要的数字...

var n = (this.id.match(/'[('d+)']/) || [])[1];

或者,如果您控制源代码,一个好的解决方案是在未来的 HTML5 支持中使用 data- 属性......

<input type="checkbox" data-number="4" name="list_code[4]" id="list_code[4]" value="AG12345678" checked="checked">

。那么在HTML5浏览器中,你可以做...

this.data.number;

。或者对于旧版支持,您可以...

this.getAttribute('data-number');

有了这个:

this.getAttribute("id").split(/'[|']/)[1];

解释:

  • this.getAttribute("id")获取 ID "list_code[4]"
  • split(/'[|']/)将其拆分为["list_code","4",""]
  • [1] 获取索引 1 处的元素,该元素4

尝试:

$('input[name^="list_code"]').each(function() {
    if ($(this).is(':checked')) 
        list_code = $(this).val();
        key = parseInt($(this).attr('name').replace(/[^0-9]/g,''));
});

如果您发现字段名称属性在索引之外具有数字,请执行以下操作:

        key = parseInt($(this).attr('name').split('[')[1].replace(/[^0-9]/g,''));