正在将json对象从变量解析为key=class所在的类

Parsing json object from a variable to classes where key = class

本文关键字:key class json 对象 变量      更新时间:2023-09-26

我正在尝试从each()对象中的变量解析json对象。

例如,我有一个长数组:

{castle: "0", commercial: "3", common: "0", cultural: "2", dioni: "0", holidays: "0", island: "2", nereides: "2", others: "0", peninsula: "0", thetis: "0"}

我有div,它们的类与数组的键的类相同。例如:

<div class="castle"></div>
<div class="commercial"></div>
<div class="common"></div>
<div class="cultural"></div>

等等。

因此,我想将每个键的值附加到class=key的类中。

$("body div").each(function(){
   var array = [] // the reall long array;
   var a = $(this).attr("class").split(' ')[0]; // in case there are two divs, split
   $("." + a).text(array.a + " hours"); // array.a doesn't work
});

在这种情况下,数组中不存在array.a,因此我无法解析每个类的每个键的值。

我该如何解决这个问题?

你为什么不换一种方式呢?使用for..in循环(本身)通过对象并设置它:

for (var key in obj) {
    $("div." + key).text(obj[key]);
}

这个循环中的选择器将找到类等于keydiv,并将相应的值附加到它

演示:http://jsfiddle.net/hungerpain/9z4zj/

但是,从你的复杂性来看,我同意你的方法是最简单的。只需将array.a更改为array[a]即可。这就是你所需要的。

试试这个:

$(document).ready(function () {
    $("body div").each(function () {
        var myarray = {
            castle: "0",
            commercial: "3",
            common: "0",
            cultural: "2",
            dioni: "0",
            holidays: "0",
            island: "2",
            nereides: "2",
            others: "0",
            peninsula: "0",
            thetis: "0"
        }; // the reall long array;
        var a = $(this).attr("class").split(' ')[0]; // in case there are two divs, split
        $("." + a).html(myarray[a] + " hours"); // array.a doesn't work
    });
});  

JSFIDDLE演示

使用array[a]而不是array.a

var obj = {castle: "0", commercial: "3", common: "0", cultural: "2", dioni: "0", holidays: "0", island: "2", nereides: "2", others: "0", peninsula: "0", thetis: "0"}
$("body div").each(function(){
   var array = [] // the reall long array;
   var a = $(this).attr("class").split(' ')[0]; // in case there are two divs, split
   $("." + a).text(obj[a] + " hours"); // array.a doesn't work
});

工作演示:http://jsfiddle.net/uNrKy/