如果您在下面運行此 javascript 代碼,
var i = 20220215155;
function increment(){
i ;
document.getElementById('period').innerHTML = i "<br />" "<hr />" ;
}
setInterval('increment()', 32100);
您將看到每 30 秒后,數字 (20220215155) 會增加,并且每個增量都會列印在新行上。例如;
**20220215156
20220215157
20220215158
20220215159
20220215160**
但我希望每個列印在每次遞增后都以這種方式排序;
**20220215160
20220215159
20220215158
20220215157
20220215156**
如果20220215156在第一行,30 秒后,20220215157應該在第一行,前面的數字自動轉到第二行,在接下來的 30 秒后,20220215158出現在第一行,依此類推。我只希望有人能理解。
請我需要幫助。
uj5u.com熱心網友回復:
insertAdjacentHTML在這里很有用。您可以使用該afterbegin屬性將包含數字的新元素添加到容器頂部。
const i = 20220215155;
const div = document.querySelector('#period');
// The function accepts a variable (the new number)
function increment(i) {
// Prepend the number to the container
div.insertAdjacentHTML('afterbegin', `<div>${i}</div>`);
// Call the function again with an incremented number
setTimeout(increment, 1000, i);
}
increment(i);
<div id="period"></div>
附加檔案
- 模板/字串文字
uj5u.com熱心網友回復:
let info = document.getElementById('info');
let num = 20220215155;
setInterval(() => {
let newElement = document.createElement('p');
newElement.innerText = num;
info.insertBefore(newElement, info.childNodes[0]); //Adding newElement at the beginning of the parent
}, 1000);
<html>
<body>
<div id="info">
</div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426577.html
標籤:javascript 算法 功能 排序 自动递增
