我正在尝试使用 jQuery .attr
函数向元素添加多个 id。但是我发现,如果我在 .attr
函数中有多个 id,则该函数会出错。
错误代码
var some_global = 0;
$('#btnName').click(function(){
var k = $("<label>", {html: "->label"});
$('<li>', {html: "list"})
.attr("id", some_global + " error") // adding multiple id cause error
.css("display"," block")
.appendTo('ul.justList')
k.appendTo("li#"+some_global);
some_global += 1;
});
我简单地浏览了文档,似乎这不一定是禁止的用法。有人能给我指明方向吗?
最佳答案
每个元素有多个 id 是无效的 HTML reference answer
In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.
为了获得这种行为,您应该使用类。
$("#some_element_id").addClass("error");
关于javascript - 使用jquery `.attr`添加多个id导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508504/