我是 JavaScript 新手,不確定這個非常基本的問題。我使用從外部 WebSocket 獲取的資料創建了一個位元幣價格更新儀表板。我設法從 WebSocket 獲取資料并將其顯示在 HTML 表上,但我只能獲取位元幣的實時價格,我還想在另一列中顯示位元幣數量。我想知道如何在一行中的 2 列中附加兩個不同的資料。我盡力解釋。
我提供了下面的代碼片段以及我從中提取資料的外部 Websocket。
注意*** 我正在從外部 websocket 中提取資料,通過該 WebSocket,我可以獲得所有詳細資訊,例如位元幣價格、數量、型別和所有內容。“messageObject.p”表示價格,“messageObject.q”表示數量。p=價格,q=數量。我能夠讓 messageObject.q(數量)顯示在表格上,但我無法在表格的另一列中顯示 messageObject.p(價格)
請讓我知道如何將行動態插入到 HTML 表中。非常感謝你提前
<table id="tableprice" class="table table-striped">
<thead>
<tr>
<th>Amount(BTC)</th>
<th scope="col">Price(USDT)</th>
</tr>
</thead>
<tbody id="pricetable" class="crypt-table-hover">
</tbody>
</table>
<script>
window.onload = () => {
function insertRow(price){
var tr = document.createElement("tr"),
tdCoin = document.createElement("td"),
tdPrice = document.createElement("td"),
docFrag = new DocumentFragment();
tdPrice.style.color="#49C279";
tdCoin.textContent = `${(price.slice(0)).toLocaleString("en-US")}`;
tdPrice.textContent = `${Number(price.slice(0,-6)).toLocaleString("en-US",{style: 'currency', currency: 'USD'})}`;
tr.appendChild(tdCoin);
tr.appendChild(tdPrice);
docFrag.appendChild(tr);
return docFrag;
}
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@aggTrade"),
table = document.getElementById("pricetable");
binanceSocket.onmessage = function(event) {
var messageObject = JSON.parse(event.data);
table.appendChild(insertRow(messageObject.q, messageObject.p));
const MAX_ROWS = 16;
const rows = table.querySelectorAll("tr");
if (rows.length > MAX_ROWS) table.removeChild(rows[0]);
}
</script>
uj5u.com熱心網友回復:
您的insertRow()函式中只有一個引數。此外,在您的insertRow()函式內部,您永遠不會嘗試從傳入的數量變數中讀取。
uj5u.com熱心網友回復:
我發現你為 insertRow 函式發送了兩個引數,而在函式中只接收一個引數并附加它。所以我嘗試編輯您的代碼,如下所示
<table id="tableprice" class="table table-striped">
<thead>
<tr>
<th>Amount(BTC)</th>
<th scope="col">Price(USDT)</th>
</tr>
</thead>
<tbody id="pricetable" class="crypt-table-hover"></tbody>
</table>
<script>
window.onload = () => {
function insertRow(numberOfCoins,price){
var tr = document.createElement("tr"),
tdCoin = document.createElement("td"),
tdPrice = document.createElement("td"),
docFrag = new DocumentFragment();
tdPrice.style.color="#49C279";
// tdCoin.textContent = `${(price.slice(0)).toLocaleString("en-US")}`;
tdPrice.textContent = `${Number(price.slice(0,-6)).toLocaleString("en-US",{style: 'currency', currency: 'USD'})}`;
tdCoin.textContent = `${numberOfCoins}`;
tr.appendChild(tdCoin);
tr.appendChild(tdPrice);
docFrag.appendChild(tr);
return docFrag;
}
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@aggTrade"),
table = document.getElementById("pricetable");
binanceSocket.onmessage = function(event) {
var messageObject = JSON.parse(event.data);
table.appendChild(insertRow(messageObject.q, messageObject.p));
const MAX_ROWS = 16;
const rows = table.querySelectorAll("tr");
if (rows.length > MAX_ROWS) table.removeChild(rows[0]);
}
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406979.html
標籤:
