在HTML复选框上访问数组的键

时间:2012-04-17 18:41:52

标签: javascript jquery

我有一个带复选框的树,他们的id有item和value的值作为它们的值。

<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。我该如何访问该值?

3 个答案:

答案 0 :(得分:3)

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];

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

<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');

答案 1 :(得分:2)

有了这个:

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

说明:

  • this.getAttribute("id")获取了身份"list_code[4]"
  • split(/\[|\]/)将其拆分为["list_code","4",""]
  • [1]获取索引1的元素4

答案 2 :(得分:1)

尝试:

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