jquery: Writing a method
Posted
by Mark
on Stack Overflow
See other posts from Stack Overflow
or by Mark
Published on 2010-05-23T07:50:44Z
Indexed on
2010/05/23
8:00 UTC
Read the original article
Hit count: 296
JavaScript
|jQuery
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.
© Stack Overflow or respective owner