javascript 为列表框中的选项获取“InvalidCharacterError: String contains an invalid character”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26114388/
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
Getting "InvalidCharacterError: String contains an invalid character" for an option in list box
提问by user1776130
I have the following line in my jsp file:
我的jsp文件中有以下行:
var option = document.createElement('<option value="NO">');
Not sure why this gives me InvalidCharacterError
.
不知道为什么这会给我InvalidCharacterError
。
Any alternatives?
任何替代方案?
回答by Gursharan Singh
You can use this code to add to your tag.
您可以使用此代码添加到您的标签中。
var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);
回答by pocjoc
There was a change in DOM implementation. Before, you could create a new element with the code inside, for instance:
DOM 实现发生了变化。之前,您可以创建一个包含代码的新元素,例如:
BAD
坏的
var anElement = document.createElement("<A HREF=\"http://stackoverflow.com \">StackOverflow</A>")
This implementation now, returns this ‘InvalidCharacterError'. What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.
现在,此实现返回此“InvalidCharacterError”。您现在必须做的是创建元素并使用 innerHTML 属性或任何节点的不同特定属性填充它。
GOOD
好的
var anElement = document.createElement("a") anElement.innerHTML = ("<A HREF=\"http://stackoverflow.com \">StackOverflow</A>")