How to take id as selector when used hash?

前端 未结 3 1720
旧巷少年郎
旧巷少年郎 2020-11-27 08:43

Suppose of the following html:

test1
test2

Now, the following wou

相关标签:
3条回答
  • 2020-11-27 09:13

    You can escape the # with backslash \:

    #test\#1{
        color: red;
    }
    

    with jQuery, you can do the same way but you need to escape the \ with another backslash:

    To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\

    $('#test\\#2').css('color','blue');
    

    Fiddle Demo

    However, # is not a valid unique identifier according to HTML 4 specification:

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    and HTML 5 specification as well:

    The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

    So you should remove second # in your id.

    0 讨论(0)
  • 2020-11-27 09:14

    you have to use \ when using special characters

    var test1 = $('#test\\#1');
    

    http://bugs.jquery.com/ticket/4944

    0 讨论(0)
  • 2020-11-27 09:26

    To use any of the meta-characters such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ as a literal part of a name, it must be escaped with with backslashes:

    css way:

    #test\#1{
        color: red;
    }
    

    jquery way:

    $('#test\\#2').css('color','blue');
    

    demo


    Recommendation:

    You should not use # in your id see more for detail

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").


    So, you may be also wondering id="test.1" can be used and for this too you should escape the character as described above.

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