How do I get a jQuery selector's expression as text?

后端 未结 9 1267
迷失自我
迷失自我 2020-11-30 10:36

I have a jQuery selector, which has a chained function.

Inside the function I want to get access to the TEXT representing the expression for the selector.

         


        
9条回答
  •  无人及你
    2020-11-30 11:24

    Please refer to my answer on a duplicate question: Intercepting selector at initialization time

    Details: 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

提交回复
热议问题