Pergunta

I have a very crude jQuery plugin wrapping a checkbox with a css styled div and hiding the actual checkbox. I run the plugin on the input element, but want the plugin to return the wrapping div for chaining, as the input element is invisible.

(function ($) {

var methods = {       

    'init': function (options) {

        var settings = $.extend({
            'location' : 'top',
            'background-color' : 'blue'
        }, options);            

        return this.each(function () {  
            var $this = $(this);
            var checked = $this.attr('checked') || '';
            $this.wrap('<div class="styled-checkboxes ' + checked + '"></div>');
            return $(this).parent('.styled-checkboxes')[0];
        });
    }           
};

$.fn.styledCheckboxes = function (method) {

    if (methods.method) {
        //
    } else if (typeof options === 'object') {
        return methods.init.apply(this, options);
    } else {
        console.log('init without options');
        return methods.init.apply(this, null);
    }        
}
})(jQuery); 

When I call the plugin like so:

console.log(
    $('input[type="checkbox"]').styledCheckboxes().after('<p>hello world</p>')
);

the appended p gets added after the checkbox, not the div, and the console trace is a jQuery selection containing any input items I had on the page, not the divs wrapping the inputs. Why is the line

return $(this).parent('.styled-checkboxes')[0];

not returning the div as the object used for chaining?

Foi útil?

Solução

The reason is because returning anything inside each does not override the returned object... the return from each is always the collection itself.

You could return the result of this.map and it should work as expected as map will still enumerate all items in the list, and you can manipulate the returned item:

return this.map(function () {  
        var $this = $(this);
        var checked = $this.attr('checked') || '';
        $this.wrap('<div class="styled-checkboxes ' + checked + '"></div>');
        return $(this).parent('.styled-checkboxes')[0];
    });

Live example: http://jsfiddle.net/wBUzP/ (The "hello world" is outside the newly added div)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top