我从套接字接收数据,我需要对这些数据进行排序和显示。 我的代码喜欢这样,但只显示未分类的数据。
$.each( data.players, function( key, value ) {
var p = value.value[0]/1000;
$('<tr>'+
'<td>'+
'<p class="price">$'+ p.toFixed(2)+'</p>'+
'</td>'+
'</tr>').appendTo('#target').hide().fadeIn(700);
});
第二个问题: 当数据被分类并显示并且套接字接收新玩家时,它应该被添加到正确的位置。
要排序的数据(每个具有id的对象都有价格atrubute): data to sort
答案 0 :(得分:0)
尝试以下
var data = {};
// simulate async data retrieval from socket
setInterval(function() {
// random data
data[parseInt(getRandom(1, 10000))] = {};
// update dome when new data is received
updateDom();
}, getRandom(1000, 5000));
// call this method each time new data is received
updateDom();
function updateDom() {
var keys = [];
// add object keys to an array to be able to sort them
for (k in data) {
if (data.hasOwnProperty(k)) {
keys.push(parseInt(k));
}
}
keys.sort(function(a, b) {
// sort values
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}).forEach(function(e) {
if ($('#target [key=' + e + ']').length === 0) {
// if we haven't printed this yet
// generate dom
var domE =
'<tr key="' + e + '"><td>' +
'<p class="price">$' + e + '</p>' +
'</td></tr>';
// get value of previous key
var prevKey = keys.indexOf(e) - 1;
prevKey = prevKey < 0 ? 0 : prevKey;
// get previous element
var keyBefore = $('#target [key=' + keys[prevKey] + ']');
// if this does not have previous key exchange html
if (keyBefore.length === 0) {
$('#target').html(domE);
} else {
keyBefore
.after(domE)
.hide()
.fadeIn(700);
}
}
});
}
// utils - ignore for real implementation
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">Data here!</div>
&#13;