当前位置:优学网  >  在线题库

如何在JavaScript中更新没有唯一id的html值?

发表时间:2022-07-29 00:46:33 阅读:190

目前,我正在开发一个网站,引导硬币市场套利信息.

我想知道下面的方法在JavaScript中是否可行.(不反应)

后端-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值吗

或者是否可以使用其他代码?还是有别的办法?

🎖️ 优质答案
  • Change your HTML so that the rows have a unique ID based on the coin name, and the columns have classes that indicate their roles.

    <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>

    Then you can find the row that corresponds to positions_data and update it:

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