Escape square brackets when assigning a class name to an element

后端 未结 4 1613
你的背包
你的背包 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]'));
    
    

    • jQuery/1.4.0 (fixed):

    $('#txtFirstname').addClass('test[someval]')
    $('#txtFirstname').attr('class')
    console.log($('#txtFirstname').hasClass('test[someval]'));
    
    

    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.
    

提交回复
热议问题