Camel case in HTML tag attributes and jquery - doesn't work, why?

后端 未结 2 491
死守一世寂寞
死守一世寂寞 2020-12-11 18:55

Yes, there are similar questions, but they are about jquery adding lowercase attributes like here: Does the attr() in jQuery force lowercase?

But I have a different

相关标签:
2条回答
  • 2020-12-11 19:54

    Instead of using ".data()" you could just use ".attr()" to access the value of the attribute, then you could reference it by the name you've given it; like the following:

    $(element).attr('data-projectId');
    
    0 讨论(0)
  • 2020-12-11 19:59

    EDIT

    The HTML spec states attribute names are case-insensitive, meaning writing them all as uppercase is as good as writing them all in lowercase or in camelCase:

    Attribute names for HTML elements may be written with any mix of lowercase and uppercase letters that are a case-insensitive match for the names of the attributes given in the HTML elements section of this document; that is, attribute names are case-insensitive.

    EDIT #2

    Another part of the spec states it more explicitly:

    All attribute names on HTML elements in HTML documents get ASCII-lowercased automatically, so the restriction on ASCII uppercase letters doesn't affect such documents.

    Original Answer

    jQuery specifies that if you want to access attributes via camelCase, then hyphenate them such that:

    data-project-id="1" is accessed via $(element).data('projectId');

    0 讨论(0)
提交回复
热议问题