javascript - 使用jquery `.attr`添加多个id导致错误

标签 javascript jquery html

我正在尝试使用 jQuery .attr 函数向元素添加多个 id。但是我发现,如果我在 .attr 函数中有多个 id,则该函数会出错。

This doesn't cause error

This cause error

错误代码

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/

相关文章:

javascript - 即使在 SUCCESS 之后,React 也会执行 PROMISE 的 CATCH 语句

javascript - 使用 jQuery 上传非拉丁名称文件

javascript - 浏览器支持 Number.EPSILON 吗?

javascript - 在 radio 和选择之间同步当前选定的项目

html - 如何在 Angular JS 中获取按钮的徽章值

javascript - JS对象与数字相加

jquery - 如何通过动态创建的 id 从 gridster.js 中删除单个小部件

javascript - jQuery:获取可能包含或不包含链接的段落标记的文本内容

javascript - 以行作为 ID 和值的表的复制按钮

java - 如何根据浏览器类型选择网页