Mark
Mark

Reputation: 33671

jquery: Writing a method

This is the same question as this: https://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.

Upvotes: 0

Views: 202

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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

Upvotes: 2

Related Questions