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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:12:24  来源:igfitidea点击:

get each child('id') into array or string

jqueryarrayseachchildren

提问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 mapfunction 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 mapfunction into a Javascript array, and then use the joinfunction to return a comma delimited string.

map函数将返回一个 jQuery 对象,其中包含“main”div 中包含的每个 div 的 id。您可以调用该get()函数将函数返回的对象map转换为Javascript 数组,然后使用该join函数返回逗号分隔的字符串。

Demo - http://jsfiddle.net/8tZXH/1

演示 - 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')