gpt4 book ai didi

javascript - 如何使用 javascript 或 jquery 将 div 数据转换为数组?

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:52 26 4
gpt4 key购买 nike

我想把这段代码转换成一个数组。

<div id="Parent">
<div class="childOne" ><span id="1dfgdffsf">ChildOne </span></div>
<div class="childOne" ><span id = "2sdfsf">ChildTwo</span> </div>
<div class="childOne" ><span id="3sdfsf">ChildThree </span></div>
<div class="childOne" ><span id="4dssfsf">ChildFour </span></div>
</div>

span id 是动态的。因此我不能使用它。请告诉我如何将它转换成数组。

最佳答案

你必须遍历每个元素并将其放入数组

//declare an array
var my_array = new Array();

//get all instances of the SPAN tag and iterate through each one
$('div#parent div.childOne span').each(function(){

//build an associative array that assigns the span's id as the array id
//assign the inner value of the span to the array piece
//the single quotes and plus symbols are important in my_array[''++'']
my_array[''+$(this).attr('id')+''] = $(this).text();

//this code assigns the values to a non-associative array
//use either this code or the code above depending on your needs
my_array.push($(this).text());

});

关于javascript - 如何使用 javascript 或 jquery 将 div 数据转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com