jQuery 将每个孩子('id')放入数组或字符串中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9729329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get each child('id') into array or string
提问by Daniel Hunter
I need to create a comma separated value for a hidden input created from a series of div id's
我需要为从一系列 div id 创建的隐藏输入创建一个逗号分隔值
<div id="main">
<div id="A"></div>
<div id="B"></div>
<div id="C"></div>
</div>
<input type="hidden" id="children"/>
I want to use jquery but having trouble with the function
我想使用 jquery 但在功能上有问题
function update_input(main){
var array = new Array();
$('#'+main).children('id').each(function(){
array.push($(this).attr('div'));
});
input_value = array.toString();
$('#children').val(input_value);
}
This is not right
这个不对
回答by Frenchi In LA
$('div','#main').each(function(){
array.push($(this).attr('id'));
});
回答by ipr101
You could use map
-
你可以使用map
-
?var arr = $("#main > div").map(function() {return this.id});
$('#children').val(arr.get().join(","));
The code above relies on your HTML being changed to -
上面的代码依赖于您的 HTML 被更改为 -
<div id="main">
<div id="A"></div>
<div id="B"></div>
<div id="C"></div>
</div>?
The map
function will return a jQuery object containing the ids of each div contained within the 'main' div. You can the call the get()
function to turn the object returned by the map
function into a Javascript array, and then use the join
function to return a comma delimited string.
该map
函数将返回一个 jQuery 对象,其中包含“main”div 中包含的每个 div 的 id。您可以调用该get()
函数将函数返回的对象map
转换为Javascript 数组,然后使用该join
函数返回逗号分隔的字符串。
Demo - http://jsfiddle.net/8tZXH/1
回答by Daniel Hunter
var ids = $('#main > td').map(function(){
return this.id
}).toArray();
$('#children').val(ids);
回答by Steve
You probably want to use children('div')
, not children('id')
您可能想要使用children('div')
,而不是children('id')