错误:SyntaxError:DOM异常12使用jQuery创建标签 [英] Error: SyntaxError: DOM Exception 12 on Tag Creation Using jQuery
问题描述
我有以下javascript:
I have the following javascript:
var orderItemQuantity = $('<input/>', {
type: 'hidden',
name: 'order_detail[][quantity]',
value: itemQuantity
});
以上JavaScript会抛出以下错误消息:
The above javascript throws the following error message:
Error: SyntaxError: DOM Exception 12
作品没有错误:
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
});
我查看了以下问题,但是答案没有明确指出正确的原因WHY。
I checked the following question but the answer did not specify clearly the correct reason WHY.
这是我的DTD:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
问题:为什么 $(' ;输入/>')
和 $('< input>')
抛出所述异常,而 $ '< li />')
不是问题?
Question: Why does $('<input/>')
and $('<input>')
throw the said exception while $('<li/>')
is not a problem?
推荐答案
确保你有jQuery加载在你的第一个例子中。
Make sure you have jQuery loaded in your first example.
即使你没有加载jQuery,函数 $()
现在由Google Chrome定义为与 querySelectorAll()
相似的东西。
Even if you don't have jQuery loaded, the function $()
is now defined by Google Chrome as something similar to querySelectorAll()
.
此函数仅接受CSS选择器参数,而不是任意的HTML,如jQuery的 $()
。
This function only accepts a CSS selector as parameter and not arbitrary HTML like jQuery's $()
.
从文档:
SYNTAX_ERR代码12已指定无效或非法字符串;
,例如设置CSSStyleRule
的selectorText属性为无效的CSS值。
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.
该函数期待一个CSS选择器,你给它HTML,所以它给了一个语法错误。
The function is expecting a CSS selector and you gave it HTML so it gave a syntax error.
看到这个小提琴,它的工作原理很好:
See this fiddle, it works just fine:
这篇关于错误:SyntaxError:DOM异常12使用jQuery创建标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!