Grab a plugin selector

Asked

Viewed 35 times

3

I’m trying to create a plugin but I can’t catch the selector, and it was even removed from version 1.9.

If I use $(this).selector in the plugin, it returns a string #div #elementoA, #div #elementoB. I’ve tried to use this.each to try to pick up individually, but I couldn’t.

I need a way that returns either an array, or an object, but with the individual selectors: '[#div #elementoA] [#div #elementoB]. It is possible using 1.9?

$('#div #elementoA, #div #elementoB').plugin()

1 answer

2


It seems that there is no more way.

To documentation even gives an example where a plugin that needs to know the selector should receive it repeated as a function parameter.

Statement example:

$.fn.foo = function( selector, options ) { /* código */ }; 

Call example:

$( "div.bar" ).foo( "div.bar", {dog: "bark"} );

Not a satisfactory answer, but the official answer.

I believe that it would be best to reformulate your code to not depend on the selector, if possible, otherwise it would be possible to create an alternative more beautiful than repetition. A very simple and unsophisticated example would be:

function applyPlugin(selector, options) {
    $(selector).plugin(selector, options);
}

If possible, edit the question explaining exactly what you failed to do with the each.

Anyway, it is the model of the use of each:

$.fn.myNewPlugin = function() {
    return this.each(function() {
        // ação em cada elemento aqui
    });
};
  • The each would just try to grab the selector individually. I never created a plugin, what I am doing is a learning, but generally I call $('#div #A, #div #B').plugin() and within the plugin I use .attr('id') to work the CSS. I’m certainly doing it wrong, so I wanted to try and catch the selector. But I’ll try to learn better. Thanks for the answer.

  • 1

    A GAMB I did was give one split : $(this).selector.split( ', ' ). Returned an array as wanted, but gambiarra is gambiarra right, never know... rs

  • @But what exactly do you need the dials for? If it is just for learning the split should work well, maybe with a more advanced regular expression become more reliable.

  • The selector #div #elementoA would give me the guarantee of only this element being manipulated. It is nothing complex, it is lack of knowledge even.

  • @Papacharlie Ever thought of counting the number of elements? Why is it important to ensure that only one element is being manipulated?

  • 1

    I put the links inside a element and in it I loop to catch each item. TKS

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.