开发者

How to know the selector inside jquery plugin?

开发者 https://www.devze.com 2023-04-11 18:14 出处:网络
I have created a plugin like jQuery.fn.Foo = function () { //var str=get selector some_how; alert(str);

I have created a plugin like

jQuery.fn.Foo = function () { 

    //var str=   get selector some_how; alert(str);      

    //at this point get selector that invoked this function

    /开发者_运维百科/eg:
    /*
         jQuery('.red').Foo(); // alerts .red
         jQuery('#something_else') // alerts  #something_else
    */


}


jQuery objects have a selector attribute. You can access this.selector.


That's how I get selector strings inside my plugins in 2017:

(function($, window, document, undefined) { 
    $.fn._init = $.fn.init
    $.fn.init = function( selector, context, root ) {
        return (typeof selector === 'string') ? new $.fn._init(selector, context, root).data('selector', selector) : new $.fn._init( selector, context, root );
    };
    $.fn.getSelector = function() {
        return $(this).data('selector');
    };
    $.fn.coolPlugin = function() {
        var selector = $(this).getSelector(); 
        if(selector) console.log(selector); // outputs p #boldText
    }
})(jQuery, window, document);

// calling plugin
$(document).ready(function() {
    $("p #boldText").coolPlugin();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>some <b id="boldText">bold text</b></p>

The idea is to conditionally wrap jQuery's init() function based on whether a selector string is provided or not. If it is provided, use jQuery's data() method to associate the selector string with the original init() which is called in the end. Small getSelector() plugin just takes previously stored value. It can be called later inside your plugin. It should work well with all jQuery versions.

0

精彩评论

暂无评论...
验证码 换一张
取 消