簡體   English   中英

如何在 JavaScript 中更新沒有唯一 ID 的 html 值?

[英]how to update html value without unique id in JavaScript?

目前,我正在開發一個指導硬幣市場套利信息的網站。

我想知道在 JavaScript 中是否可以使用以下方式。(不是 React)

后端 - django

def index(request):
    data = [{"name": "BTC", "binance": "price1", "gecko": "price2", "ftx": "price3"}, 
            {"name": "ETH", "binance": "price1", "gecko": "price2", "ftx": "price3"}]
       
    return render(request, 'index.html', context={'data': data})

html -

<table class="table table-striped mb-0 fixed">
          <thead>
          <tr>
              <th>name</th>
              <th>binance</th>
              <th>gecko</th>
              <th>ftx</th>
          </tr>
          </thead>
          <tbody>
          {% for d in data %}
              <tr>
                  <td>{{ d.name }}</td>
                  <td>{{ d.binance }}</td>
                  <td>{{ d.ftx }}</td>
                  <td>{{ d.okx }}</td>
              </tr>
          {% endfor %}
          </tbody>
</table>

JS-

var socket = new WebSocket(
    'ws://' + window.location.host +
    '/ws?session_key=${sessionKey}')

socket.onmessage = function (e) {
    let positions_data = JSON.parse(e.data)
    
    //if positions_data {"site": "binance", "price": "27000", "name": "BTC"}
    //update data -> 
    data = [{"name": "BTC", "binance": "27000", "gecko": "price2", "ftx": "price3"}, 
            {"name": "ETH", "binance": "price1", "gecko": "price2", "ftx": "price3"}]

    //do something?
    //then change html value



    }

是否可以僅通過更改 JS 中的變量來更改 html 值

或者是否可以采取額外的代碼? 還是有其他方法?

更改您的 HTML 以使行具有基於硬幣名稱的唯一 ID,並且列具有指示其角色的類。

<table class="table table-striped mb-0 fixed">
          <thead>
          <tr>
              <th>name</th>
              <th>binance</th>
              <th>gecko</th>
              <th>ftx</th>
          </tr>
          </thead>
          <tbody>
          {% for d in data %}
              <tr id="row-{{d.name}}">
                  <td class="name">{{ d.name }}</td>
                  <td class="binance">{{ d.binance }}</td>
                  <td class="ftx">{{ d.ftx }}</td>
                  <td class="okx">{{ d.okx }}</td>
              </tr>
          {% endfor %}
          </tbody>
</table>

然后你可以找到對應於positions_data的行並更新它:

let row = document.querySelector(`#row-${positions_data.name}`);
let site = positions_data.site;
row.querySelector(`.${site}`).innerText = positions_data.price;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM