在 javascript 中动态创建元素和 class 实现

Dynamic creation of element and class implementation in javascript

我在使用 innerHTML 在 javascript 中动态创建元素时遇到问题。这是代码:

var newElement  = document.createElement("tr");
newElement.innerHTML = ['<td><a href="javascript:void(0);">Test Suite</a></td><td>4,977</td><td class="text-align-center">',
                      '<div class="sparkline txt-color-blue text-align-center" data-sparkline-height="22px" data-sparkline-width="90px" data-sparkline-barwidth="2">2700, 3631, 2471, 1300, 1877, 2500, 2577, 2700, 3631, 2471, 2000, 2100, 3000</div>',
            ].join('\n');

$("#locationsGraph").append(newElement);

问题是Element创建的刚刚好,但是元素class没有实现。

有了这一部分:

class="sparkline txt-color-blue text-align-center" data-sparkline-height="22px" data-sparkline-width="90px" data-sparkline-barwidth="2"

我应该得到一个条形图,但我得到的是相同的数字列表。

它与 innerHTML 中 class 的实现有关吗? 我也尝试手动创建所有元素并分配 className 但结果是相同的

根据the docs,您需要运行 $(newElement).find('div').sparkline()

您没有匹配您的

的结尾
newElement.innerHTML = ['<td><a href="javascript:void(0);">Test Suite</a></td><td>4,977</td><td class="text-align-center">',
                      '<div class="sparkline txt-color-blue text-align-center" data-sparkline-height="22px" data-sparkline-width="90px" data-sparkline-barwidth="2">2700, 3631, 2471, 1300, 1877, 2500, 2577, 2700, 3631, 2471, 2000, 2100, 3000</div>',
          '</td>' //this is missing
  ].join('\n');