ID/Class Selector

前端 未结 5 941
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 20:32

I have some kind of problem with jQuery selectors.

Let\'s say i want to select $(\'#elementID\') but the elementID is a variable.

相关标签:
5条回答
  • 2021-01-14 20:50

    If elementID is a variable ala var elementID = '#someId', I would suggest simply (although I didn't try it ):

    $(elementID)
    

    jQuery/JavaScript should dereference this variable as a string value and wrap the ID correctly for further operations...

    0 讨论(0)
  • 2021-01-14 20:53

    I use $('#'+variable) all the time.

    0 讨论(0)
  • 2021-01-14 20:59

    Not really, no. You need "#" as a selector to select an ID. No reason to not use the ID selector. Or you could write your own function, something like:

    $.id = function(id)
    {
        return $("#" + id);
    }
    
    var elementID = "elementID";
    $.id(elementID).text();
    

    That would return an element with the ID of "elementID" without having to use the "#". Kind of pointless though.

    0 讨论(0)
  • 2021-01-14 21:04

    Not sure what you mean, but:

    var variable = '#' + elementID;
    
    $(variable)...
    
    0 讨论(0)
  • 2021-01-14 21:05

    The following is probably the fastest and the cleanest solution:

    $(document.getElementById(elementID))
    

    Appending your variable to "#" would work of course, but it's inherently slower.

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