Why doesn't this jquery selector with a period work

后端 未结 9 1990
长发绾君心
长发绾君心 2020-12-06 04:56

I have a div with an ID

this jquery selector works

$(\"[id^=\'updates-pane         


        
相关标签:
9条回答
  • 2020-12-06 05:17

    $("#updates-pane-user\\.followed_on") - This Should work as per the Jquery documentation

    // Does not work
     $("#some:id")
    
     // Works!
     $("#some\\:id")
    
     // Does not work
     $("#some.id")
    
     // Works!
     $("#some\\.id")
    
    0 讨论(0)
  • 2020-12-06 05:17

    yes Jimbo answer is correct, but you can still make that work with escaping character with \\

    $("#updates-pane-user\\.followed_on")
    

    Escape with TWO (2) backslashes.

    Check this link for How do I select an element by an ID that has characters used in CSS notation?

    0 讨论(0)
  • 2020-12-06 05:22

    Because . selector considers that there is a class with the following name

    $("#updates-pane-user.followed_on")
    

    means : find all elements with id = updates-pane-user which have class name followed_on

    0 讨论(0)
  • 2020-12-06 05:22

    For sure period creating problem for JQuery to recognise the pattern.

    jQuery has three type of selectors:

    1. "." selector means to select an element by class name.
    2. "#" selector means to select an element by ID.
    3. And Element selector that selects elements by their name(div, input etc.)

    And you have confused jQuery engine with your naming convention of ID.

    Its assuming that there is a div with id="updates-pane-user" and a applied class="followed_on". In such cases jQuery suggest to escape sequence using //. Below should be your syntex to select the element.

    $("#updates-pane-user\\.followed_on");
    

    Check it out this wrong fiddle and try to correct using // : http://jsfiddle.net/ukJ8Z/

    Cheers!!

    0 讨论(0)
  • 2020-12-06 05:28

    In the latter selector, . is used to denote a class. So it's looking for the .followed_on class, which it obviously doesn't find and so nothing is matched.

    In order to fix this, I think you should escape the dot with a double-backslash:

    $("#updates-pane-user\\.followed_on")

    According to the jQuery docs:

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

    In general, try not to use periods or other special characters in your IDs to avoid confusion all around. "Allowed" is not the same as "good practice."

    0 讨论(0)
  • 2020-12-06 05:32

    You can also use the id attribute selector, like:

    $('[id="updates-pane-user.followed_on"]')
    

    because jQuery will treat the attribute as a string, rather than a jQuery class selector.

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