所以这是我第一次在jquery上使用JSON,我对我想做的事情以及任何帮助都有所了解,或者指出正确的方向将非常感激。
我的HTML设置如下:
<div id="agriculture" class="btn"><div>
<div id="treasurer" class="btn"><div>
<div id="war" class="btn"><div>
..... (about 16 of these)
<div id="content_container">
<div id="title"></div>
<img id="photo" src="" />
<div id="summary"></div>
</div>
然后我计划设置一堆JSON变量,如下所示:
var agriculture = {
"title": "Secretary of Agriculture",
"location": "url for photo used",
"summary": "summary of cabinet position"
};
var treasurer = {
"title": "Secretary of the Treasury",
"location": "url for photo used",
"summary": "summary of cabinet position"
};
var war = {
"title": "Secretary of War",
"location": "url for photo used",
"summary": "summary of cabinet position"
};
这里设置的目标是当你单击“.btn”时它会获取attr('id')并使用它来调用JSON中的正确变量,因为它们匹配然后将该内容放入更正内容容器的divs / img src。
这是一种合理的做法吗?如果有人或不是某人向我推动正确的方向?
非常感谢您的帮助!
答案 0 :(得分:3)
最好将值存储在具有命名键的字典结构中,而不是创建自变量。这是一个例子:
var data = {
agriculture: {"title" : "Secretary of Agriculture",
"location" : "url for photo used",
"summary" : "summary of cabinet position"
},
treasurer: {"title" : "Secretary of the Treasury",
"location" : "url for photo used",
"summary" : "summary of cabinet position"
}
};
然后访问您的对象:
$('.btn').click(function(){
var id = $(this).attr('id');
console.log(data[id]);
});
答案 1 :(得分:1)
那不是JSON,那是Javascript对象的文字。 JSON是一种表示数据的文本格式。
如果您已全局声明变量,则可以将它们作为window
对象的成员进行访问:
$('.btn').click(function(){
var id = $(this).attr('id');
var obj = window[id];
$('#title').text(obj.title);
$('#photo').attr('src', obj.location);
$('#summary').text(obj.summary);
});
答案 2 :(得分:1)
JSON
只是 JavaScript Object Notation ,通过执行var foo = { bar : "foobar" }
,您实际上正在创建object literal
并将其属性存储在变量中。
使用元素的id
是一个坏主意,因为id
应该是元素的唯一标识符,而不是数据存储。在我的示例中,我使用了data-attribute
,但这可能是您想要的任何内容。
<a href="#" class="data-accessor" data-attribute="foo">Click this for foo!</a><br />
<a href="#" class="data-accessor" data-attribute="bar">Click this for bar!</a><br />
var data = {
foo : "You clicked foo!",
bar : "You clicked bar!"
}
$('a.data-accessor').click(function() {
var me = $(this);
alert(data[me.attr('data-attribute')]);
return false;
});
查看this jsfiddle以查看其实际效果。
这是一个包含多个数据点http://jsfiddle.net/gSgyP/
的示例答案 3 :(得分:0)
我会做这样的事情:
var data = {
agriculture: {
title: "Secretary of Agriculture",
location: "url for photo used",
summary: "summary of cabinet position"
},
treasurer: {
title: "Secretary of the Treasury",
location: "url for photo used",
summary: "summary of cabinet position"
},
war: {
title: "Secretary of War",
location: "url for photo used",
summary: "summary of cabinet position"
}
};
var $title = $('#title');
var $photo = $('#photo');
var $summary = $('#summary');
$('.btn').on('click', function () {
console.log( data[this.id] );
$title.html( data[this.id].title );
$photo.attr('src', data[this.id].location );
$summary.html( data[this.id].summary );
});