Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - Getting initial selector inside jquery plugin

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

Lets say you have a plugin like this

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

how can I get the #box as a string in the plugin? Not sure if that's the correct way of doing it, and any other solution would be great as well.

Considering #box is a select dropdown,

The problem I'm having is if I do the regular javascript

$('#box').val(x);

The correct option value gets selected,

but if i try the same inside a plugin

.....
this.each(function() {
var $this = $(this);


$this.val(x);

the last code doesn't really do anything.

I notice I'm having trouble targeting #box inside the plugin because it's a object and not a string...

Any help would be appreciated.

Thanks!

Edit:: Putting in the code I'm working in for better understanding

(function($){
$.fn.customSelect = function(options) {
    var defaults = {
        myClass : 'mySelect'
    };
    var settings = $.extend({}, defaults, options);


    this.each(function() {
        // Var          
        var $this = $(this);
        var thisOpts = $('option',$this);
        var thisSelected = $this[0].selectedIndex;
        var options_clone = '';

        $this.hide();

        options_clone += '<li rel=""><span>'+thisOpts[thisSelected].text+'</span><ul>'
        for (var index in thisOpts) {
            //Check to see if option has any text, and that the value is not undefined
            if(thisOpts[index].text && thisOpts[index].value != undefined) {
                options_clone += '<li rel="' + thisOpts[index].value + '"><span>' + thisOpts[index].text + '</span></li>'
            }
        }
        options_clone += '</ul></li>';

        var mySelect = $('<ul class="' + settings.myClass + '">').html(options_clone); //Insert Clone Options into Container UL
        $this.after(mySelect); //Insert Clone after Original

        var selectWidth = $this.next('ul').find('ul').outerWidth(); //Get width of dropdown before hiding
        $this.next('ul').find('ul').hide(); //Hide dropdown portion

        $this.next('ul').css('width',selectWidth);

        //on click, show dropdown
        $this.next('ul').find('span').first().click(function(){
            $this.next('ul').find('ul').toggle();
        });

        //on click, change top value, select hidden form, close dropdown
        $this.next('ul').find('ul span').click(function(){
            $(this).closest('ul').children().removeClass('selected');
            $(this).parent().addClass("selected");
            selection = $(this).parent().attr('rel');
            selectedText = $(this).text();
            $(this).closest('ul').prev().html(selectedText);
            $this.val(selection); //This is what i can't get to work
            $(this).closest('ul').hide();
        });

    });
    // returns the jQuery object to allow for chainability.
    return this;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Note: This API has been removed in jQuery 3.0. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set. 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"} ); with the "div.bar" selector repeated as the first argument of .foo().

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...