javascript 使用 document.createElement() 时出现“字符串包含无效字符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18396411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:45:26  来源:igfitidea点击:

'String contains an invalid character' when using document.createElement()

javascript

提问by Sora

var NewRow = document.createElement("<tr><td align='left' valign='top'  width='9%;'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td></tr>");

I am getting an error:

我收到一个错误:

InvalidCharacterError: String contains an invalid character

How can I fix this?

我怎样才能解决这个问题?

回答by ruakh

The string you pass to document.createElementis the type of the element, e.g. tr.

您传递给的字符串document.createElement是元素的类型,例如tr.

If you really want to assemble your HTML as a big string, I suppose you could write:

如果你真的想把你的 HTML 组装成一个大字符串,我想你可以这样写:

var newRow = document.createElement('tr');
newRow.innerHTML = "<td align='left' valign='top'  width='9%;'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td>";

but it's probably cleaner/faster/safer to use DOM manipulation for the whole thing.

但在整个过程中使用 DOM 操作可能更干净/更快/更安全。

回答by MarmiK

The recent answer will do fine, I have one similar answer below: here, I have defined the elements so that it will be easy to change and debug.

最近的答案会很好,我在下面有一个类似的答案:在这里,我已经定义了元素,以便于更改和调试。

var ProfilePic = "abl.jpg";
var Msg="Hi";
var Date = "June 10, 2010";
function doit() {
   var NewRow ="<tr><td align='left' valign='top'  width='9px'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td></tr>";
   var element = document.getElementById("tbl_body");
   element.innerHTML +=NewRow;
}

this works like charm to me..

这对我来说很有吸引力..

The problem with the previous code was createElementwhere you have to create row, then tdthen text and then append.

前面代码的问题是createElement你必须先创建行,td然后是文本,然后是追加。

I hope this will do..

我希望这会做..

回答by Imran Khan



Check this out:

看一下这个:

Creating a new DOM element from an HTML string using built-in DOM methods or prototype

使用内置 DOM 方法或原型从 HTML 字符串创建新的 DOM 元素

You can not pass HTML string to createElement method, instead use innerHTML property as shown in the above link.

您不能将 HTML 字符串传递给 createElement 方法,而是使用上面链接中显示的 innerHTML 属性。