【发布时间】:2018-03-15 11:53:40
【问题描述】:
我有一个我希望访问的 JSON 文件,基于 HTML 选项值属性。
我可以访问数据并挑选出一些东西,但就像我之前写的那样,我喜欢根据从列表中选择的内容来做。
所以我想在 json 文件中用 p 映射选项值属性。
所以我的列表看起来像这样
<div>
<select id="places">
<option>Choose city...</option>
<option value="Place1">Place1</option>
<option value="Place2">Place2</option>
<option value="Place3">Place3</option>
</select>
</div>
我的 JSON 看起来像这样:
{
data: [{
date: "2018031406",
p: [{
lon: -7.777,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100225.25,
temperature: 4.34227,
wind - dir: 122.00003,
wind - speed: 13.022041,
weather - symbol: 3
},
{
lon: -6.666,
lat: xxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100230.75,
temperature: 3.77977,
wind - dir: 120.87503,
wind - speed: 13.006416,
weather - symbol: 3
}
]
},
{
date: "2018031407",
p: [{
lon: -7.777,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100225.25,
temperature: 4.34227,
wind - dir: 122.00003,
wind - speed: 13.022041,
weather - symbol: 3
},
{
lon: -6.666,
lat: xxxxx,
precip - intensity: 0.046875,
pressure - sealevel: 100230.75,
temperature: 3.77977,
wind - dir: 120.87503,
wind - speed: 13.006416,
weather - symbol: 3
}
]
}
]
}
所以布局是基于现在的时间,所以我在jQuery中设置了这个:
jQuery(document).ready(function() {
var location = 'folder/folder2/folder3/area/area.json';
jQuery.getJSON(location, function(json) {
function pad2(n) {
return n < 10 ? '0' + n : n
}
var date_now = new Date();
date_test = date_now.getFullYear().toString() + pad2(date_now.getMonth() + 1) + pad2(date_now.getDate()) + pad2(date_now.getHours());
var index = json.data.findIndex(function(item, i) {
return item.date === date_test
});
//This I can use to see which index number is the current hour
//I have weather data a couple of hours backwards, and alot forward (in time).
//console.log(index);
//Manually fetch data
/*--------------------Temperature--------------------------------------*/
//Lets say - index+1 is date: "2018031407" and p[1] is the second p from json file - which indicates the hour now +1 (date) and area (p).
var some_temp = JSON.stringify(json.data[index + 1].p[1]["temperature"]);
//console.log(some_temp);
var some_temp2 = Math.round(some_temp);
console.log(some_temp2);
jQuery(".div_temp").prepend(some_temp2);
/*------------------------Temperature ends----------------------------------------*/
});
});
我应该如何处理这项任务?上路有困难。我在这方面是个菜鸟。
一个例子是 Place1 应该等于 p[0],Place2 应该等于 p[1] 等等...
【问题讨论】:
-
不清楚你的问题是什么。如果您需要使用数字,那么只需使用数字?
value="0"等等,然后他们匹配? -
是的,那将是完美的......但是如何实现它......所以如果我选择值为 0 的 Place1,它将如何遍历温度部分?
-
我的意思是它会将温度部分中的 p[1] 更改为 p[0]。
-
您当前的构建会根据“精确”相同的时间找到正确的数据字段。如果您的 JSON 中的日期不是 == 当前日期时间,您希望发生什么?去下一个约会?到最近的日期了吗?
-
温度部分唯一应该改变的是 p 匹配一个区域,它应该匹配列表中的一个选项。
标签: javascript jquery html json