Get the current jQuery selector string?

前端 未结 8 1921
北恋
北恋 2020-12-01 18:00

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

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

Would like to output my_se

相关标签:
8条回答
  • 2020-12-01 18:22

    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.

    0 讨论(0)
  • 2020-12-01 18:27

    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.

    0 讨论(0)
  • 2020-12-01 18:29

    With selector deprecated i use

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

    just two lines of code

    or if you're really cheap with lines

    select = $("#category option[value=#{document.getElementById('category').value}]")[0].innerHTML
    
    0 讨论(0)
  • 2020-12-01 18:29

    Fully working with any jQuery version even after deprecation and removal of "selector" property

    My solution is to intercept the selector at the time of jQuery object initialization and in the same time maintain all other jQuery functionalities transparently all this using inheritance as the following:

    $ = (function (originalJQuery) 
    {
        return (function () 
        {
            var newJQuery = originalJQuery.apply(this, arguments);
            newJQuery.selector = arguments.length > 0 ? arguments[0] : null;
            return newJQuery;
        });
    })($);
    
    $.fn = $.prototype = jQuery.fn;
    

    Usage:

    var myAnchors = $('p > a');
    var selector = myAnchors.selector;
    

    Should produce: "p > a"

    Tried it successfully with jQuery 3.4.1

    0 讨论(0)
  • 2020-12-01 18:31

    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
    
    0 讨论(0)
  • 2020-12-01 18:41
    jQuery.fn.getSelector = function() {
            return this.data('selector');
    };
    
    0 讨论(0)
提交回复
热议问题