在HTML复选框*问数组的密钥

问题描述:

我有一个带复选框的树,它们的ID具有项目和值的键作为它们的值。在HTML复选框*问数组的密钥

<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]在这案件。我如何获得这个价值?

+0

答案为止似乎有点小题大做。出于好奇,你如何渲染你的复选框? – 2012-04-17 18:53:42

+0

'['和']'对于'id'属性无效。 http://*.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – iambriansreed 2012-04-17 18:55:45

+0

@iambriansreed:除非你在一个只需要定位HTML5浏览器的环境中。然后他们很好。 – 2012-04-17 18:58:47

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

-1嘿,我想现在有四种正确的解决方案是不够的... – 2012-04-17 18:50:37

+0

+1,但我通常不会对我与 – ajax333221 2012-04-17 18:55:59

+0

@ ajax333221竞争的答案投票:这是一场竞赛吗? ;)我提出了其他答案,甚至事情了。 – 2012-04-17 18:57:08

有了这个:

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,'')); 
+1

这是有风险的,他可以有'list2_code [4]'并且转到'24' – ajax333221 2012-04-17 18:53:11