views:

45

answers:

1

This is the same question as this: http://stackoverflow.com/questions/2890620/jquery-running-a-function-in-a-context-and-adding-to-a-variable

But that question was poorly posed.

Trying again, I'm trying to do something like this:

I have a bunch of elements I want to grab data from, the data is in the form of classes of the element children.

<div id='container'>
    <span class='a'></span>
    <span class='b'></span>
    <span class='c'></span>
</div>
<div id='container2'>
    <span class='1'></span>
    <span class='2'></span>
    <span class='3'></span>
</div>

I have a method like this:

jQuery.fn.grabData = function(expr) {
    return this.each(function() {
        var self = $(this);             
        self.find("span").each(function (){
            var info = $(this).attr('class');
            collection += info;
        });
    });
};

I to run the method like this:

var collection = '';
$('#container').grabData();
$('#container2').grabData();

The collection should be adding to each other so that in the end I get this

console.log(collection);

:

abc123

But collection is undefined in the method. How can I let the method know which collection it should be adding to?

Thanks.

+2  A: 

If you want to accumulate values for every call of the grabData function you will need a global variable:

var collection = '';
jQuery.fn.grabData = function(expr) {
    return this.each(function() {
        var self = $(this);             
        self.find('span').each(function () {
            var info = $(this).attr('class');
            collection += info;
        });
    });
};

If on the other hand you want to do it only for single call of the grabData function you could do this:

jQuery.fn.grabData = function(expr) {
    var collection = '';
    this.each(function() {
        var self = $(this);             
        self.find('span').each(function () {
            var info = $(this).attr('class');
            collection += info;
        });
    });
    return collection;
};

And then use it like this:

var collection = $('#container').grabData();
console.log(collection);
Darin Dimitrov
For the first type, is that not the same thing I had in my question? That gives the error collection is not defined.
Mark
Not exactly the same. Put `var collection = ''` **outside** of the `document.ready` function. I suppose that in your case you put it inside as you are using the plugin just after.
Darin Dimitrov
Ahah, thank you.
Mark