我有一个不同城市的列表,我必须按离我最近的位置排序。
这是小提琴:http://jsfiddle.net/t24g3umj/
var jsonString ='{"City A":{"Position":{"Longitude":9.96233,"Latitude":49.80404}},"City B":{"Position":{"Longitude":6.11499,"Latitude":50.76891}},"City C":{"Position":{"Longitude":6.80592,"Latitude":51.53548}},"City D":{"Position":{"Longitude":9.50523,"Latitude":51.31991}},"City E":{"Position":{"Longitude":9.66089,"Latitude":48.70158}},"City F":{"Position":{"Longitude":9.93368,"Latitude":53.55608}},"City G":{"Position":{"Longitude":11.56122,"Latitude":48.14496}},"City H":{"Position":{"Longitude":13.34253,"Latitude":52.5319}},"City I":{"Position":{"Longitude":6.11327,"Latitude":50.77715}},"City J":{"Position":{"Longitude":13.36671,"Latitude":52.54344}}}';
var myData = JSON.parse(jsonString);
$(document).ready(function () {
var distanceObj = [],
i = 0;
$.each(myData, function (a, b) {
distanceObj[i] = {
distance: hesapla(9.9608999, 49.7222842, b.Position.Longitude, b.Position.Latitude),
location: a
};
++i;
});
distanceObj.sort(function (a, b) {
return parseInt(a.distance) - parseInt(b.distance)
});
$.each(distanceObj, function (a, b) {
$('#groups').append('<li>' + b.location + ': ' + b.distance + 'm</li>');
});
console.log(distanceObj);
function hesapla(meineLongitude, meineLatitude, long1, lat1) {
erdRadius = 6371;
meineLongitude = meineLongitude * (Math.PI / 180);
meineLatitude = meineLatitude * (Math.PI / 180);
long1 = long1 * (Math.PI / 180);
lat1 = lat1 * (Math.PI / 180);
x0 = meineLongitude * erdRadius * Math.cos(meineLatitude);
y0 = meineLatitude * erdRadius;
x1 = long1 * erdRadius * Math.cos(lat1);
y1 = lat1 * erdRadius;
dx = x0 - x1;
dy = y0 - y1;
d = Math.sqrt((dx * dx) + (dy * dy));
return Math.round(d * 1000);
};
});
我想知道如何让每个li元素都可点击?
另外,第二个问题是如何将特殊城市过滤到列表顶部而不管距离是多少?
先感谢stackoverflow的精彩社区。 p>
答案 0 :(得分:1)
on
在处理程序上使用委托事件绑定,前提是您要动态添加li:
$(document).ready(function () {
$('#groups').on('click', 'li', function() {
// handler here
}
.prepend()
将li添加到列表顶部,而不是将append()
添加到底部
$('#groups').prepend('<li>I am special ...</li>');
答案 1 :(得分:0)
这是你想要的吗?
$.each(distanceObj, function(a, b) {
$('#groups').append('<li><a href="#">' + b.location + ': ' + b.distance + 'm </a></li>');
});
答案 2 :(得分:0)
要使元素可点击,您需要在每个li中使用"<a>"
标记。以下是修改后的代码。
$.each(distanceObj, function(a, b) {
$('#groups').append('<li><a href="#">' + b.location + ': ' + b.distance + 'm </a></li>');
});