Javascript DOMParser.parseFromString giving parse error

老子叫甜甜 提交于 2019-12-13 05:32:19

问题


When doing this in console, why do I get a parse error?

TR = '<TR id=line1 class="myClass"><INPUT id=input1 type=hidden> <INPUT id=input2> <TD style="PADDING-LEFT: 20px" align=left> <IMG class=im border=0 src="images/img.gif"> Hello </TD><!-- comment --> <TD id=cell1 align=right></TD> <TD id=cell2 align=right></TD> <TD align=middle>&nbsp; </TD> <TD align=middle></TD></TR>';
parser = new DOMParser()
xmlDocument = _parser.parseFromString(TR, "text/xml");

回答1:


First problem (I assume it's not the one you're experiencing, rather that this code is erroneously copy-pasted): Your variable name is parser, not _parser.

Your main problem is that you're trying to parse HTML as XML, which will work IF your HTML is also valid XML. But yours isn't. Quote your attributes for a start. That's what

error on line 1 at column 8: AttValue: " or ' expected

means.

After you do that, close your void elements. It's OK to leave off the trailing slash in HTML5, but not within the stricter rules of XML.




回答2:


You create a new DOMParser() and assign it to a variable named parser:

parser = new DOMParser()

But then you reference an undeclared variable _parser on the next line:

xmlDocument = _parser.parseFromString(TR, "text/xml");

If you replace _parser with parser, the console error should go away.



来源:https://stackoverflow.com/questions/35759582/javascript-domparser-parsefromstring-giving-parse-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!