![](/img/trans.png)
[英]How to get d3 to recognize push+shift as an add-new-object-to-end and remove-old-object-from-beginning, rather than as just a data change in place
[英]How to insert new data before old data rather than after
我執行php腳本以顯示隨機數據。 我使用ajax get從php腳本獲取數據,並繼續每1秒從php腳本獲取數據。 如果計數大於或等於4,我還將執行最后一行的刪除。但是,我的輸出是向后的。 我想在舊數據之前附加新數據。
PHP腳本
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
HTML代碼
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var $auto_refresh = setInterval(function() {
var $count = $('#result div').length;
while ($count >= 4) {
$('result div:last-child').remove();
$count = $('#result div').length;
}
updateServer();
}, 1000);
//Remove last div if the count is more than 4
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').append(val); //i want to insert before in other words new data appear at the top and old data remain down
}
</script>
</body>
</html>
我想到了使用before或insertbefore在舊數據之前插入新數據。 我也用過node來插入,這行不通。 請幫我。 謝謝..
您必須使用jquery的prepend() :
function randomdata(val) {
$('#result').prepend(val);
}
編輯
我注意到另一個錯誤: $('result div:last-child').remove();
應該是$('#result div:last-child').remove();
這可能就是為什么它不改變的原因,當它在4格時不會刪除並重做計數,因此您陷入了困境……下面的修復應該可以解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.