繁体   English   中英

如何从<span>具有多个标签的</span>多个<span>s中</span>获取所有数据<span>到数组中?</span>

[英]How can I get all data from multiple <span>s with multiple tags into an array?

我正在寻找从多个跨度中获取多个跨度标签并将其粘贴到数组(或json对象)中以供以后使用的最佳实践。 (甚至不确定要使用数组还是json。)

HTML:

<span class="car" id=c1 data-make="volvo" data-year="2010">Car1<span>
<span class="car" id=c2 data-make="saab" data-year="1998">Car2<span>

js:

var cars = document.getElementsByClassName('car');
for(var i=0; i<cars.length; i++) { 
  <what goes best here?>
}

目前,我已经为每个ID,数据和年份创建了3个平面数组,但这似乎很麻烦。 我在弄清楚如何创建时遇到了麻烦:

    Array(
[0] => Array(
        [id] => c1 
        [make] => volvo
        [year] => 2010
    )
[1] => Array(
        [id] => c2
        [make] => SAAB  
        [year] => 1998    
    )
);

或json对象:

jsonString = [
    {
        "id": "c1",
        "make": "volvo",
        "year": "2010",
    },
    {
        "id": "c2",
        "make": "saab",
        "year": "1998", 
    }
];

我对此的需求很简单。 我将使用该信息对innerHTML进行一些简单的替换,例如:

document.getElementById(car[id]).innerHTML = car[make]

因此,分为两个部分:1)对于这种类型的任务,多维数组或json对象有什么更好的选择? 2)我的循环部分将数据粘贴到该数组或json中的内容是什么?

谢谢-我还在学习。

您可以遍历每个元素的所有属性,并将每个data-属性添加到相应的对象:

var result = [],
    pattern = /^data-/;

// don't access the 'length' property of a live list in each iteration,
// cache it instead
for(var i = 0, l = cars.length; i < l; i++) { 
    var element = cars[i],
        attrs = element.attributes,
        car = {};

    // setting the ID
    car.id = element.id;

    // iterating over all attributes
    for(var j = 0, jl = attrs.length; j < jl; j++) {
        var name = attrs[j].name;
        if(pattern.test(name)) { // if the attribute name starts with 'data-'
            // remove the 'data-' part and add the value to the current object
            car[name.replace(pattern, '')] = attrs[j].value;
        }
    }

    // add the object to the final list
    result.push(car);
}

演示

如果您愿意使用jQuery,则可以使用以下内容。 否则,请使用Felix的答案。

您应该使用对象数组,如下所示:

var arr = [];
$("span").each(function(i) {
    arr[i] = {};
    arr[i]["id"] = $(this).attr("id");
    arr[i]["make"] = $(this).data("make");
    arr[i]["year"] = $(this).data("year");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM