Javascript:appendChild() 出现意外令牌非法错误
我是 javascript 新手,但我在这行代码中遇到了“意外令牌非法”错误:
switch (city) {
case "london":
var newdiv = document.createElement('<div id="london" class="option-area"><label class="city">From London to…?</label>
<select class="city">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br /></div>');
document.all.bookingform.appendChild(newdiv);
break;
}
这可能是一个非常愚蠢的错误,但我已经尝试了几个小时来让这个块正常工作。请帮忙!
I'm new to javascript, but I'm getting an "Unexpected Token ILLEGAL" error with this line of code:
switch (city) {
case "london":
var newdiv = document.createElement('<div id="london" class="option-area"><label class="city">From London to…?</label>
<select class="city">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br /></div>');
document.all.bookingform.appendChild(newdiv);
break;
}
It's probably a very dumb mistake, but I've tried for hours to get this block working. Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码中有几个错误:
1)
document.createElement()< /code> function
采用单个参数作为元素名称,而不是 HTML/XML 片段来解析和构建 DOM 树。但是,您可以通过构建匿名包装元素并设置其内部 HTML,然后将其第一个子元素附加到目标元素来实现您的目标,例如:
2)字符串不能跨越多行,但您可以构建一个多行字符串,如下所示:
如果您实际上想要在字符串中添加换行符,您可以在字符串文字中使用换行符转义序列 (
\n
),例如'Hello\nnewline!'
。[编辑]
当然,如果您只是想将 HTML 附加到文档正文中已有的元素,您可以这样做:
但是请注意,在修改上述表单时,各种浏览器中都会存在一些怪癖;考虑使用 JavaScript 库,例如 jQuery、ExtJS 或 Prototype.js。
There are a couple errors in your code:
1) The
document.createElement()
function takes a single argument as the element name, not an HTML/XML snippet to parse and build a DOM tree. However you chould achieve your goal by building an anonymous wrapper element and setting its inner HTML, then appending its first child to the target element, for example:2) Strings cannot span multiple lines but you can build a multiline string like this:
If you actually want newlines in the string you can use the newline escape sequence (
\n
) in a string literal, like'Hello\nnewline!'
.[Edit]
Of course, if you're just trying to append HTML to an element already in the document body you do this:
Note however that there are quirks in various browsers when modifying forms such as above; consider using a JavaScript library such as jQuery, ExtJS, or Prototype.js.
document.createElement
用于创建一个元素 - 类似于document.createElement('div')
,因此不允许传递 HTML。您可以创建该元素,然后使用ref_to_the_div.innerHTML = ""
更改它的 HTMLdocument.createElement
is used to create one element - likedocument.createElement('div')
, so passing HTML is not allowed. You could create the element, then change the HTML for it later withref_to_the_div.innerHTML = "<some html="goes here" />"