Javascript 将json平面文件数据动态加载到新<;李>;元素
我正在尝试使用json平面文件数据来:Javascript 将json平面文件数据动态加载到新<;李>;元素,javascript,jquery,json,ajax,flat-file,Javascript,Jquery,Json,Ajax,Flat File,我正在尝试使用json平面文件数据来: 生成新的列表项 在新列表项中填充特定类 我的json文件如下所示: { "event": { "title": "Title of thing", "preface": "Preface for thing", "cost": "00", "image": "img/image.jpg", "source": "website name", "tags": [ "identifier-1",
{
"event": {
"title": "Title of thing",
"preface": "Preface for thing",
"cost": "00",
"image": "img/image.jpg",
"source": "website name",
"tags": [
"identifier-1",
"identifier-2"
]
},
"event": {
"title": "Title of thing",
"preface": "Preface for thing",
"cost": "00",
"image": "img/image.jpg",
"source": "website name",
"tags": [
"identifier-1",
"identifier-2"
]
}
}
<script>
$.getJSON( "events.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
// no clue what to put here.
}).appendTo( "dateCards ul" );
});
</script>
我希望输出标记如下所示:
<li class="event">
<div class="top">
<p class="preface">Preface for thing</p>
<div class="price">
<div class="money">$</div>
<div class="cost">00</div>
</div>
</div>
<div class="middle">
<div class="title">Title of thing</div>
<img class="image" src="img/image.jpg" />
<p class="source">website name</span></p>
</div>
<div class="bottom">
<button>view details</button>
<div>
</li>
事物的序言
$
00
物名
网站名称
查看详细信息
最后,问题是,我的javascript如下所示:
{
"event": {
"title": "Title of thing",
"preface": "Preface for thing",
"cost": "00",
"image": "img/image.jpg",
"source": "website name",
"tags": [
"identifier-1",
"identifier-2"
]
},
"event": {
"title": "Title of thing",
"preface": "Preface for thing",
"cost": "00",
"image": "img/image.jpg",
"source": "website name",
"tags": [
"identifier-1",
"identifier-2"
]
}
}
<script>
$.getJSON( "events.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
// no clue what to put here.
}).appendTo( "dateCards ul" );
});
</script>
$.getJSON(“events.json”,函数(数据){
var项目=[];
$。每个(数据、函数(键、值){
//不知道该在这里放什么。
}).附录(“dateCards ul”);
});
这应该给你一个起点。您需要完成每个“事件”属性的其余处理
然后可以将代码简化为以下内容:
{
"event1": {
//...
},
"event2": {
//...
}
}
var事件={
“事件1”:{
“头衔”:“事物的头衔”,
“序言”:“事物的序言”,
“成本”:“00”,
“image”:“img/image.jpg”,
“来源”:“网站名称”,
“标签”:[
“标识符-1”,
“标识符-2”
]
},
“事件2”:{
“头衔”:“事物的头衔2”,
“序言”:“事物的序言2”,
“成本”:“01”,
“image”:“img/image.jpg”,
“来源”:“网站名称2”,
“标签”:[
“标识符-1”,
“标识符-2”
]
}
};
$.each(事件、函数(键、值){
var liHtml='\
\
\
\
$\
\
\
\
\
\
\
\
\
\
查看详细信息\
\
';
var html=$(liHtml);
$.each(val,函数(propertyName,propertyValue){
交换机(propertyName){
案例“图像”:
$(html).find(“.”+propertyName).prop(“src”,propertyValue);
打破
违约:
$(html).find(“.”+propertyName).text(propertyValue);
打破
}
});
$(“#日期卡”).append(html);
});代码>
您可以尝试使用模板功能:
const=newutil();
$.getJSON(“events.json”,函数(数据){
var template=35;.template($('#template_event').html();
$。每个(数据、函数(键、值){
$(“ul”).append(模板(val));
});
});
函数Util(){
this.template=函数(str){
var regex=/()/g;
var matches=str.match(regex);
如果(匹配){
返回函数(obj){
var-str2=str;
对于(var i=0;i
$
" />
查看详细信息