Js为.append动态表的未终止字符串常量

时间:2013-10-09 13:43:55

标签: javascript

我正在使用数组中的数据动态创建表:

var toAppend = $("#tablediv");
toAppend.append("<table id=\"grid\"><tr><th>(labels)</th>");
for (var f = 0; f < seriescount; f++)
{
    toAppend.append("<th>" + series[f] + "</th>");
}
toAppend.append("</tr></table>");

最后一行返回'未终止的字符串常量'错误。通过删除行或更改其内容来消除这种情况 - 这与它作为结束标记有关。

此代码位于C#Razor中的标签中。

1 个答案:

答案 0 :(得分:0)

文档片段始终关闭。你不能追加半个元素。

所以当你这样做时

toAppend.append("<table id=\"grid\"><tr><th>(labels)</th>");

你真正做的是

toAppend.append("<table id=\"grid\"><tr><th>(labels)</th></tr></table>");

这里一个简单的解决方案是构建一个HTML字符串,并只使用完整的字符串执行一个append

var h = "<table id=grid><tr><th>(labels)</th>";
for (var f = 0; f < seriescount; f++) {
    h += "<th>" + series[f] + "</th>";
}
h += "</tr></table>";
$("#tablediv").append(h);