如何通过document.createElement向动态创建的元素添加唯一类

时间:2019-11-02 16:57:53

标签: ajax

我将JSON响应文本输出到表中。该表是动态创建的。

如何更改代码,以使生成的每个thtd元素都分配一个唯一的类名?重新加载脚本时,类名称不应更改。 th x 5和td x 5

  function loadAnalysis() {
    var xhttp = new XMLHttpRequest();
    var url = document.getElementById("url").value;
    if (url == "") {
      alert("Please enter URL");
      return;
    }
    xhttp.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        var data = this.responseText;
        var jsonResponse = JSON.parse(data);
        console.log(jsonResponse["lighthouseResult"]);
        var table = document.createElement('table');
        table.setAttribute('class', 'result');
        var properties = ['performance', 'accessibility', 'best-practices', 'seo', 'pwa'];
        var capitalize = function(s) {
          return s.charAt(0).toUpperCase() + s.slice(1);
        }
        var tr = document.createElement('tr');
        for (var i = 0; i < properties.length; i++) {
          var th = document.createElement('th');
          th.appendChild(document.createTextNode(capitalize(properties[i])));
          tr.appendChild(th);
        }
        table.appendChild(tr);
        var tr, row;
        console.log("jsonResponse", jsonResponse);
        var categories = Object.keys(jsonResponse["lighthouseResult"]);
        for (var r = 0; r < categories.length; r++) {
          tr = document.createElement('tr');
          row = jsonResponse["lighthouseResult"][categories[r]];
          for (var i = 0; i < properties.length; i++) {
            var td = document.createElement('td');
            td.appendChild(document.createTextNode(row[properties[i]].score));
            tr.appendChild(td);
          }
          table.appendChild(tr);
        }
        document.getElementById('analysisTable').appendChild(table);
      }
    };
    xhttp.open("GET", "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + encodeURIComponent(url) +
      "&fields=lighthouseResult%2Fcategories%2F*%2Fscore&prettyPrint=false&strategy=desktop&category=performance&category=pwa&category=best-practices&category=accessibility&category=seo&key=AIzaSyDSNxhf0capOwppqlg9wZJUvzBewxf6mHU", true);
    xhttp.send();
  }

1 个答案:

答案 0 :(得分:0)

也许不是最干净的编码方式,但它对我来说却是javascript noob的窍门

对于th元素:

th.classList.add("category");

对于td元素:

        var ids = 'performance,accessibility,best-practices,seo,pwa'.split(',');
        for (var i = 0; i < properties.length; i++) {
        var td = document.createElement('td');
          td.id = ids[i];