簡體   English   中英

從 JS 文件 (HTML/JQuery) 更新 HTML 數據

[英]Updating HTML data from JS file (HTML/JQuery)

我正在制作一個冠狀病毒跟蹤網站,但無法在 HTML 文件中自動更新數據。 這是我的 JS 代碼:

(async()=>{
    // define some globals
  var update = async()=>{

    // download the data
    console.log('Report: Download Started');
    var url = 'https://cov19.cc/report.json?v='+Math.random();
    var res = await fetch(url);
    var report = await res.json();

    // set the last updated time
    $('#last_updated').text(moment.utc(report.last_updated).fromNow());

    // get variable data
    var world = report.regions.world;

    var total_confirmed = report.regions.world.totals.confirmed;
    document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit();

    var total_critical = world.totals.critical;
    document.getElementById("total_critical").innerHTML = total_critical.commaSplit();

    var total_deaths = world.totals.deaths;
    document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit();

    var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered);
    document.getElementById("total_active").innerHTML = total_active.commaSplit();

    var total_recovered = world.totals.recovered;
    document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit();

    // hide the loading icon
    $('#loader').hide();
    };

    // store last updated date
    var old_last_updated;

    // check for the last update
    var update_check = async()=>{
    console.log('Checking for updates');
    var res = await fetch('https://cov19.cc/last_updated.txt');
    var last_updated = await res.text();

    // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data
    if(old_last_updated == last_updated)return;
    old_last_updated = last_updated;

    update();
    };

    // initialize
    update_check();

    // check for updates every 60 seconds
    setInterval(update_check, 60000);
})();

    //cov19 prototypes
    String.prototype.commaSplit = function() {
    return this.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };
    Number.prototype.commaSplit = String.prototype.commaSplit;

這就是我在 HTML 文件中顯示數據的方式:

<p style="font-size: 60px; color: #F5F2D0; 
                            text-align: center; font-weight: 600; margin-bottom: 0";
                            id="total_confirmed">
                        </p>

數據僅在我刷新頁面時更改,我怎樣才能使其自動更新而無需刷新頁面? 我認為由於變量在更新 function 中,它們會自動更改。 我必須在我的 HTML 代碼中調用 function 嗎? 我已經堅持了很長時間,非常感謝您的幫助。 我對 JQuery 還是新手,所以這可能是一個簡單的修復。 謝謝

我認為你的代碼工作得很好。 您看不到任何更新,因為

if(old_last_updated == last_updated)return;
old_last_updated = last_updated;

這是決定是否要更新 DOM 的明智檢查(如果數據沒有更改,那么為什么要更新?)

我只是在此檢查之前添加了一個時間戳,以顯示 DOM 更新(沒有問題),因此您的檢查不會讓它更新。 (我還更改了更新檢查的頻率,以便測試更容易:從 60 秒改為 10 秒。)

 (async() => { // define some globals var update = async() => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); var res = await fetch(url); var report = await res.json(); // set the last updated time jQuery('#last_updated').text(moment.utc(report.last_updated).fromNow()); // get variable data var world = report.regions.world; var total_confirmed = report.regions.world.totals.confirmed; document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit(); var total_critical = world.totals.critical; document.getElementById("total_critical").innerHTML = total_critical.commaSplit(); var total_deaths = world.totals.deaths; document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit(); var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered); document.getElementById("total_active").innerHTML = total_active.commaSplit(); var total_recovered = world.totals.recovered; document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit(); // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); console.log('last_updated.txt:', last_updated) // just to see that your code updates: $('#query_time').text(Date.now()); // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(); }; // initialize update_check(); // check for updates every 60 seconds setInterval(update_check, 10000); })(); //cov19 prototypes String.prototype.commaSplit = function() { return this.toString().replace(/\B(?=(\d{3})+(?,\d))/g, ";"); }. Number.prototype.commaSplit = String.prototype;commaSplit;
 .display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="query_time"></div>

添加

這是您的代碼的一些修改版本:

 (async() => { // define some globals var update = async(text, updateTime) => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); var res = await fetch(url); var report = await res.json(); // set the last updated time jQuery('#last_updated').text(moment.utc(report.last_updated).fromNow() + ` queried: ${updateTime}`); // get variable data var world = report.regions.world; var total_confirmed = report.regions.world.totals.confirmed; document.getElementById("total_confirmed").innerHTML = total_confirmed.commaSplit() + ` queried: ${updateTime}`; var total_critical = world.totals.critical; document.getElementById("total_critical").innerHTML = total_critical.commaSplit() + ` queried: ${updateTime}`; var total_deaths = world.totals.deaths; document.getElementById("total_deaths").innerHTML = total_deaths.commaSplit() + ` queried: ${updateTime}`; var total_active = world.totals.confirmed - (world.totals.deaths + world.totals.recovered); document.getElementById("total_active").innerHTML = total_active.commaSplit() + ` queried: ${updateTime}`; var total_recovered = world.totals.recovered; document.getElementById("total_recovered").innerHTML = total_recovered.commaSplit() + ` queried: ${updateTime}`; // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); console.log('last_updated.txt:', last_updated) // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data // if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(last_updated, Date.now()); }; // initialize update_check(); // check for updates every 60 seconds setInterval(update_check, 10000); })(); //cov19 prototypes String.prototype.commaSplit = function() { return this.toString().replace(/\B(?=(\d{3})+(?,\d))/g, ";"); }. Number.prototype.commaSplit = String.prototype;commaSplit;
 .display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="total_confirmed"></div> <div id="total_critical"></div> <div id="total_deaths"></div> <div id="total_active"></div> <div id="total_recovered"></div>

在這里,我刪除了明智的更新檢查並將查詢時間添加到顯示的所有字符串的末尾 - 您可以看到它們很好地更新(間隔 10 秒)。 沒問題。

小東西

 (async() => { // define some globals var update = async(text, updateTime) => { // download the data console.log('Report: Download Started'); var url = 'https://cov19.cc/report.json?v=' + Math.random(); try { var res = await fetch(url); var report = await res.json(); } catch (err) { console.log(err) } // set the last updated time document.getElementById('last_updated').innerHTML = moment.utc(report.last_updated).fromNow() + `<br />query time: ${new Date(Date.now())}<br /><br />` // adding total confirmed document.getElementById('total_confirmed').textContent = 'TOTAL CONFIRMED: ' + report.regions.world.totals.confirmed.toLocaleString('en-US') // set data list document.getElementById('data_container').innerHTML = createHTMLTemplate(report.regions.world.totals) // hide the loading icon $('#loader').hide(); }; // store last updated date var old_last_updated; // check for the last update var update_check = async() => { console.log('Checking for updates'); var res = await fetch('https://cov19.cc/last_updated.txt'); var last_updated = await res.text(); // if the last updated date is newer than the stored last updated date then update the variable and update the table with the new data // if (old_last_updated == last_updated) return; old_last_updated = last_updated; update(last_updated, Date.now()); }; // initialize update_check(); // check for updates every 10 seconds setInterval(update_check, 10000); })(); function createHTMLTemplate(data) { let html = '' for (let key in data) { html += `<div>${key}: ${data[key].toLocaleString('en-US')}</div>` } html += `<div>active: ${(data.confirmed - (data.deaths + data.recovered)).toLocaleString('en-US')}</div>` return html }
 .display-class { /*font-size: 60px; color: #F5F2D0; text-align: center; font-weight: 600; margin-bottom: 0;*/ }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script> <p id="total_confirmed" class="display-class">TOTAL CONFIRMED</p> <div id="last_updated"></div> <div id="data_container"></div>

您可以通過以下方式使代碼更易於維護 - 將代碼提取到函數中(例如創建 HTML 模板) - 刪除不必要的函數( commaSpit()就是這樣的 function - toLocaleString('en-US')也一樣(以及更多)

我在jsfiddle上試過你的代碼。

一件事 - 在您在問題中顯示的p標簽中:

你放了; 在您的style屬性中的"之后。所以改變它。


我沒有做其他更改,它正在工作:

https://jsfiddle.net/17w0d2pq/

如果您仍然無法讓它在您的系統上運行,請添加您在console中遇到的錯誤。

暫無
暫無

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

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