Get the current jQuery selector string?

2020-01-29 08:33发布

问题:

When calling a custom plugin, how can I get the current selector string?

$('my_selector p').my_plugin();

Would like to output my_selector p within my script. How can I access this string?

回答1:

You can use selector property:

$('my_selector p').selector // my_selector p

version deprecated: 1.7, removed: 1.9



回答2:

Post selector deprecation v. 1.7:

If you're only dealing with ids and classes as selectors you can use the following:

var selector = (typeof($(this).attr('id')) !== 'undefined' || $(this).attr('id') !== null) ? '#' + $(this).attr('id') :  '.' + $(this).attr('class');

There are cleaner ways but since the removal of .selector due to being inconsistent between browsers since 1.7, this has been my go-to.



回答3:

Being deprecated, the official advice is to add the selector as a parameter in your function call: https://api.jquery.com/selector/

Plugins that need to use a selector string within their plugin can require it as a parameter of the method. For example, a "foo" plugin could be written as

$.fn.foo = function( selector, options ) { /* plugin code goes here */ };

and the person using the plugin would write

$( "div.bar" ).foo( "div.bar", {dog: "bark"} );

Redundant, yes, but it's always reliable.



回答4:

jQuery.fn.getSelector = function() {
        return this.data('selector');
};


回答5:

With sector deprecated i use

index = document.getElementById('category').value
select = $("#category option[value=#{index}]")[0].innerHTM

just two lines of code

or if you're really cheap with lines

select = $("#category option[value=#{document.getElementById('category').value}]")[0].innerHTML


回答6:

Best workaroud is

function mySelector(selector) {
    return $.extend($(selector),{"selector":selector});
}

this returns classic jquery object as $() would

mySelector(".myClass")

and this returns string of the selector

mySelector(".myClass").selector


回答7:

Extending to kevinmicke's answer : You can get the selector in your event object that you pass on callback functions.

In callback functions

event.handleObj.selector

Example:

You'll get the selector string in e.handleObj.selector

    $( '.container' )
    .on('change', 'select.mySelector', function (e) {
        console.log(JSON.stringify(e));
        $('.selector').text(e.handleObj.selector);
        $('.value').text($(this).val());
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <select class="mySelector">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <h3>Your Selector: <span class="selector"></span></h3>
  <h3>Selected Value: <span class="value"></span></h3>
  
</div>

Console Log gives an object like this:

{
    // ...skipped lines
    "handleObj": {
        "type": "change",
        "origType": "change",
        "guid": 1,
        "selector": "select.mySelector",
        "needsContext": false,
        "namespace": ""
    }
}