Escape square brackets when assigning a class name to an element

后端 未结 4 1611
你的背包
你的背包 2020-12-09 01:05

Does anyone know how to escape the square bracket character when setting a class name with jQuery?

Try the following:

$(\'#txtFirstname\').addClass(\         


        
相关标签:
4条回答
  • 2020-12-09 01:47

    Short answer: you don't need to escape brackets because the argument is a class name, not a selector. It didn't work for you because of a bug in earlier jQuery versions that has long been fixed.

    To demonstrate it, here's your code running under different versions:

    • jQuery/1.3.2 (buggy):

    $('#txtFirstname').addClass('test[someval]')
    $('#txtFirstname').attr('class')
    console.log($('#txtFirstname').hasClass('test[someval]'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <div id="txtFirstname"></div>

    • jQuery/1.4.0 (fixed):

    $('#txtFirstname').addClass('test[someval]')
    $('#txtFirstname').attr('class')
    console.log($('#txtFirstname').hasClass('test[someval]'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    <div id="txtFirstname"></div>

    So the issued was apparently fixed on jQuery/1.4.0. I found a ticket regarding this (though it's tagged as being fixed on 1.4.2 rather than 1.4.0).

    I insist: the rule to quote or escape metacharacters with \\ in order to use them as a literal part of a name only applies to selectors. However, the .hasClass() method does not receive a selector as argument but as class name:

    .hasClass( className )
    
        className
        Type: String
        The class name to search for.
    
    0 讨论(0)
  • 2020-12-09 01:50

    The introduction of jQuery API page gives the above explanation about this:

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

    0 讨论(0)
  • 2020-12-09 01:59

    Escape with TWO (2) backslashes.

    http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

    0 讨论(0)
  • 2020-12-09 01:59

    If the selector is contained within a variable (or if you can get it into a variable), the code below may be helpful:

    selector_name = $this.attr('class');
    //e.g selector_name = users[0][first:name]
    
    escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
    //e.g escaped_selector_name = users\\[0\\]\\[first\\:name\\]
    

    In short we prefix all special characters with double backslash. Here's some additional documentation from the jQuery site:

    http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

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