You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Binance API项目:WebSocket比特币实时价格无法在input显示的解决求助

解决Binance WebSocket数据无法在input显示的问题

问题根源

你代码里的h1和input用了同一个id btc-price,HTML规定id必须唯一,document.getElementById只会返回第一个匹配的元素(也就是h1),所以input完全没被操作到,自然不会显示数据。另外,input的内容是通过value属性设置,不是innerText,这也是要注意的点。

修复步骤及代码

  1. 修改HTML,给input设置唯一id
    把input的id改成btc-price-input,避免和h1冲突:
<h1 id="btc-price"></h1>
<input type="text" id="btc-price-input" value="" />
  1. 修改JavaScript,同时操作两个元素
    分别获取h1和input元素,h1用innerText更新内容,input用value属性更新:
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let priceHeading = document.getElementById('btc-price');
let priceInput = document.getElementById('btc-price-input');
let lastPrice = null;

weburl.onmessage = (event) => {
  let stockObject = JSON.parse(event.data);
  let price = parseFloat(stockObject.p).toFixed(2);
  
  // 更新h1的颜色和内容
  priceHeading.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
  priceHeading.innerText = price;
  
  // 更新input的内容
  priceInput.value = price;
  
  lastPrice = price;
};

这样修改后,WebSocket返回的比特币价格就能同时在h1和input里正常显示了。

内容的提问来源于stack exchange,提问作者Vivek Vivi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:24:14