javascript 错误:SyntaxError:使用 jQuery 创建标签时出现 DOM 异常 12
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15714601/
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
Error: SyntaxError: DOM Exception 12 on Tag Creation Using jQuery
提问by nmenego
I have the following javascript:
我有以下 javascript:
var orderItemQuantity = $('<input/>', {
type: 'hidden',
name: 'order_detail[][quantity]',
value: itemQuantity
});
The above javascript throws the following error message:
上面的 javascript 抛出以下错误信息:
Error: SyntaxError: DOM Exception 12
This one works without error:
这个工作没有错误:
var newListItem = $('<li/>', {
html:
$('#item_name_'+itemId).text() +
'(' + $('#item_quantity_' + itemId).val() +')' +
'<a onclick="removeItem(' + itemId + ')">Delete this</a>' +
'<input type="hidden" name="order_detail[][item_id]" value="' + itemId + '"/>',
id: itemId
});
I checked the following questionbut the answer did not specify clearly the correct reason WHY.
我检查了以下问题,但答案没有明确说明正确的原因 WHY。
Here is my DTD:
这是我的 DTD:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Question: Why does $('<input/>')
and $('<input>')
throw the said exception while $('<li/>')
is not a problem?
问题:为什么$('<input/>')
并$('<input>')
抛出上述异常而$('<li/>')
没有问题?
回答by Heinrich Lee Yu
Make sure you have jQuery loaded in your first example.
确保在第一个示例中加载了 jQuery。
Even if you don't have jQuery loaded, the function $()
is now defined by Google Chrome as something similar to querySelectorAll()
.
即使您没有加载 jQuery,该函数$()
现在也被 Google Chrome 定义为类似于querySelectorAll()
.
This function only accepts a CSS selector as parameter and not arbitrary HTML like jQuery's $()
.
这个函数只接受一个 CSS 选择器作为参数,而不是像 jQuery 的$()
.
From the docs:
从文档:
SYNTAX_ERR code 12 In invalid or illegal string has been specified; for example setting the selectorText property of a CSSStyleRule with an invalid CSS value.
SYNTAX_ERR 代码 12 已指定无效或非法字符串;例如,使用无效的 CSS 值设置 CSSStyleRule 的 selectorText 属性。
The function is expecting a CSS selector and you gave it HTML so it gave a syntax error.
该函数需要一个 CSS 选择器,而你给了它 HTML,所以它给出了一个语法错误。
See this fiddle, it works just fine:
看到这个小提琴,它工作得很好: