簡體   English   中英

將唯一 ID 設置為從 JSON 文件在 JavaScript 中創建的表格單元格

[英]Setting unique ID to a table cell created in JavaScript from a JSON file

我在 JavaScript 中創建表格單元格和行,並在表格單元格中添加來自 JSON 文件的信息。 我在我的代碼中為表格單元格分配了一個唯一的 id,但我收到錯誤,提示 id 未定義,並且當我稍后想在 id 上使用它們時,id 為“空白”。

我不明白為什么會這樣! 請注意,表已創建,一切都如我所願。 下面你可以看到我的代碼和其他相關信息,請不要使用jQuery,謝謝!

HTML:

<div id="info">
    <table id="country">
    </table>
</div>

JavaScript:

            document.getElementById("country").innerHTML = "";
            for (var i = 0; i < jsonData.api.countries.length; i = i + 2) {
                document.getElementById("country").innerHTML += "<tr><td id = '" + jsonData.api.countries[i].code + "' > " + "<img src=" + jsonData.api.countries[i].flag + ">" + "<p>" + jsonData.api.countries[i].country + "</p>" + "</td>" +
                    "<td id = '" + jsonData.api.countries[i + 1].code + "' > " + "<img src=" + jsonData.api.countries[i + 1].flag + ">" + "<p>" + jsonData.api.countries[i + 1].country + "</p>" + "</td>"
                    +"</tr>";


                }

我在控制台日志中得到的錯誤:

Uncaught TypeError: Cannot read property 'code' of undefined
at XMLHttpRequest.myfunction

這是 html 在頁面元素中的樣子的圖片:

在此處輸入圖片說明

jsonfile 示例:

在此處輸入圖片說明

無法讀取未定義的屬性“x”意味着您正在嘗試訪問空對象的屬性。 嘗試記錄 jsonData.api.countries[i+1]。 我的猜測是,一旦到達 for 循環的最后一個索引,您就會嘗試訪問不存在的 i+1 對象。 您可能希望繼續 for 循環,直到jsonData.api.countries.length-1為止。

嗨,這是一個使用 vanilla js 和一些自定義 json 的示例:

 let json = { "countries": [{ "country": "Albania", "code": "AL", "flag": "https://media.api-football.com/flags/al.svg" }, { "country": "Algeria", "code": "DZ", "flag": "https://media.api-football.com/flags/dz.svg" }, { "country": "Honduras", "code": "HN", "flag": "https://media.api-football.com/flags/hn.svg" } ] }; let html = ``; json.countries.forEach((e, i) => { html += `<tr><td id="${e.code}" onclick="infoCountry(this)"><img src="${e.flag}"></img><p>${e.country}</p></td><tr>`; }); document.getElementById('country').innerHTML = html; const infoCountry = (target) => { let country = target.querySelectorAll('p')[0].innerText; alert('this country is ' + country) }
 <div id="info"> <table id="country"> </table> </div>

希望能幫助到你

暫無
暫無

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

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