正在将json对象从变量解析为key=class所在的类
Parsing json object from a variable to classes where key = class
我正在尝试从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]);
}
这个循环中的选择器将找到类等于key
的div
,并将相应的值附加到它
演示: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/
相关文章:
- RegEx删除空属性?例如,如果(class=“”||class=“”)移除;否则就下课
- 当浏览器上的后退按钮到达主页时,我需要删除Class
- 通过id和class属性获取元素
- KeyPress和Keydown在这个特定的代码上不起作用.只有key-up起作用
- 菜单栏class=活动引导程序主题无法正常工作
- $(.class).empty总是缺少一个元素
- 如何获取文本框组的值,并使用jquery将它们放入(key:Value)数组中
- jQuery[button.class]未检测到用按钮追加行
- javascript点击函数不;不适用于ID和Class
- HTML class=Ajax操作,如何让类点击调用好的操作
- Add a class if var < 0 jquery
- 将鼠标悬停在Angular JS中的一个元素上,并将Class添加到另一个元素中
- Difference between methods of defining JavaScript 'class
- todomvc Backbone's更改为class'编辑'使todo可编辑
- 使用jQuery隐藏和显示具有相同Class的类
- JQuery选择器:如果同级具有.class,则选择td
- jQuery:具有class但不具有$(this)的元素
- 使用lodash从对象数组中获取uniq[key,value]
- Why does "document.querySelector('a.some class'
- 正在将json对象从变量解析为key=class所在的类