如何获得包含在一个div中的单选按钮的ID
我想要得到一个使用javascript或jquery的div中包含的所有单选按钮的列表。如何获得包含在一个div中的单选按钮的ID
例如
<div id="container">
<input type="radio" id="1">
<input type="radio" id="2">
<input type="radio" id="3">
.... //total no of radio buttons are not known
</div>
我想含有包含在DIV所有单选按钮的ID的数组。
arr[0]="1"
arr[1]="2"
arr[2]="3"
...
..
var array = new Array();
$('#container input:radio').each(function (index) {
array[index] = $(this).attr('id');
});
这一个不会有几个原因工作。 1)你没有指定输入; 2)'$(this)'是一个数组。以你的方式工作,你需要使用'$(this)[0] .id' – 2010-07-22 06:29:34
如果收音机包含在#container中的嵌套div中,这个工作吗? – 2010-07-22 06:34:15
@Ionut,我在你的评论之前修改了代码;) – 2010-07-22 06:41:44
var ids = $('#container :radio').map(function() { return this.id; }).get();
这可能工作:
var arr= [];
$('#container :radio').each(function(){
arr.push({ "the_id": this.id, "val":this.value })
});
//right now you have a json like array with ID and value and you can access it by `arr[0].the_id` and `arr[0].val`
只能推的ID(没有价值,所以没有花括号需要),您可以访问元素,如arr[0]
另外考虑[jQuery.map](http://api.jquery.com/map/) – 2010-07-22 06:27:20
http://api.jquery.com/map/中的第一个示例完成了您所要求的操作,您只需要适当地更改选择器即可。 – 2010-07-22 06:28:38