Getting initial selector inside jquery plugin

前端 未结 4 895
天涯浪人
天涯浪人 2020-12-09 03:27

I got some help earlier regarding selectors, but I\'m stuck with the following.

Lets say you have a plugin like this

$(\'#box\').customplugin();


        
相关标签:
4条回答
  • 2020-12-09 04:04

    Because of the deprecation and removal of jQuery's .selector, I have experimented with javascript's DOM Nodes and came up with a 2017 and beyond solution until a better way comes along...

    //** Get selector **//
    
        // Set empty variables to work with
        var attributes = {}, // Empty object 
            $selector = ""; // Empty selector
    
        // If exists... 
        if(this.length) {
            // Get each node attribute of the selector (class or id) 
            $.each(this[0].attributes, function(index, attr) {
                // Set the attributes in the empty object
                // In the form of name:value
                attributes[attr.name] = attr.value;
            }); 
        }
        // If both class and id exists in object        
        if (attributes.class && attributes.id){
            // Set the selector to the id value to avoid issues with multiple classes
            $selector = "#" + attributes.id
        }
        // If class exists in object
        else if (attributes.class){
            // Set the selector to the class value
            $selector = "." + attributes.class
        }
        // If id exists in object
        else if (attributes.id){
            // Set the selector to the id value
            $selector = "#" + attributes.id
        }
        // Output
        // console.log($selector);
        // e.g: .example   #example
    

    So now we can use this for any purpose. You can use it as a jQuery selector... eg. $($selector)

    EDIT: My original answer would only get the attribute that appears first on the element. So if we wanted to get the id that was placed after the class on the element, it wouldn't work.

    My new solution uses an object to store the attribute information, therefore we can check if both or just one exists and set the required selector accordingly. With thanks to ManRo's solution for the inspiration.

    0 讨论(0)
  • 2020-12-09 04:11

    This page talks about getting the selector:

    http://api.jquery.com/selector/

    0 讨论(0)
  • 2020-12-09 04:13

    Just a heads-up: .selector() is deprecated in jQuery 1.7 and removed in jQuery 1.9: api.jquery.com/selector. – Simon Steinberger

    Use the .selector property on a jQuery collection.

    var x = $( "#box" );
    alert( x.selector ); // #box
    

    In your plugin:

    $.fn.somePlugin = function() {
    
        alert( this.selector ); // alerts current selector (#box )
    
        var $this = $( this );
    
        // will be undefined since it's a new jQuery collection
        // that has not been queried from the DOM.
        // In other words, the new jQuery object does not copy .selector
        alert( $this.selector );
    }
    

    However this following probably solves your real question?

    $.fn.customPlugin = function() {
        // .val() already performs an .each internally, most jQuery methods do.
        // replace x with real value.
        this.val(x);
    }
    
    $("#box").customPlugin();
    
    0 讨论(0)
  • 2020-12-09 04:14

    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 讨论(0)
提交回复
热议问题