[英]Websocket data is appearing in an h1 element, but not in an input
I am working on a Binance API project for getting the live price of Bitcoin.我正在研究 Binance API 项目,以获取比特币的实时价格。 I wrote some Javascript code to do this.
我写了一些 Javascript 代码来做到这一点。
The issue is that it is not working in an input
but it is working in a h1
.问题是它不在
input
中工作,但在h1
中工作。 I need it to work in the input
.我需要它在
input
中工作。 How can I do this?我怎样才能做到这一点?
<h1 id="btc-price"></h1>
<input type="text" id="btc-price" value="" />
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElement = document.getElementById('btc-price');
let lastPrice = null;
weburl.onmessage = (event) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
stockPriceElement.innerText = price;
lastPrice = price;
};
The issue is because you've created two HTML elements with the same id
, which is invalid.问题是因为您创建了两个具有相同
id
的 HTML 元素,这是无效的。 id
must be unique. id
必须是唯一的。 In addition, the method used to update the content of an h1
and an input
are different.另外,
h1
和input
的内容更新方法不同。
To set the value of the input
, select it from the DOM and set its value
property, like this:要设置
input
的值,select 从 DOM 中设置它的value
属性,如下所示:
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade'); let stockPriceInput = document.querySelector('#btc-price'); let lastPrice = null; weburl.onmessage = (event) => { let stockObject = JSON.parse(event.data); let price = parseFloat(stockObject.p).toFixed(2); stockPriceInput.style.color =?lastPrice || lastPrice === price: 'black'? price > lastPrice: 'green'; 'red'. stockPriceInput;value = price; lastPrice = price; };
<input type="text" id="btc-price" value="" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.