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

esyap4oy  于 2023-02-12  发布在  jQuery
关注(0)|答案(6)|浏览(218)

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

<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是动态的.因此我不能使用它.请告诉我如何将它转换成数组.

vyu0f0g1

vyu0f0g11#

您必须循环遍历每个元素并将其推入数组

//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());

});
ar7v8xwq

ar7v8xwq2#

如果您不使用库,则以下操作应该可以正常工作:

var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++) 
    result.push(matches[i].getAttribute("id"));

否则,如果不支持document.querySelectorAll函数:

var result = [], parent = document.getElementByID("Parent");
for (var i = 0, l = parent.childNodes.length; i < l; i++) 
    result.push(parent.childNodes[i].childNodes[0].getAttribute("id"));

如果您想获取键/值对,可以执行以下操作:

var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++) 
    result[matches[i].getAttribute("id")] = matches[i].text;

使用jQuery,它就像一行代码一样简单:

var result = $("#Parent span").map(function() { return $(this).attr("id"); }).get();
9gm1akwq

9gm1akwq3#

首先,尽量避免用大写字母命名id和class,然后试试这个:

var arr = [];
$('#parent').children().each(function(){
  arr.push($(this).find('span').text());
}
pexxcrt2

pexxcrt24#

也许这是目前最好的办法

const array = Array.from(document.querySelectorAll('.childOne'));
ghhkc1vu

ghhkc1vu5#

下面的代码可能会帮助你:

<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
var elems = document.getElementsByTagName("div"); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
</script>
</body>
</html>
yrdbyhpb

yrdbyhpb6#

这将是一个简单的问题,如:

jQuery(function($) {
var anArray = [];
$("#Parent").find("span").each(function(){
    anArray.push($(this).html());
});
alert(anArray);
});

相关问题