Getting initial selector inside jquery plugin

前端 未结 4 901
天涯浪人
天涯浪人 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: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();
    

提交回复
热议问题