user947668
user947668

Reputation: 2718

passing jquery object with data to function

How do you a pass jQuery object with data to a function?

For example i have the following object:

var el = $('#myelement').data('test1','yay1')
                    .data('test2','yay2')
                    .data('test3','yay3');

and additional functions to process object data:

jQuery.fn.allData = function() {
    var intID = jQuery.data(this.get(0));
    return(jQuery.cache[intID]);
};

function checkIt (myobj){
  $.each($(myobj).allData(), function(key, value) {
    alert(key + "=" + value);
  });
}

Then I call the checkIt function and pass myelement:

checkIt(el);

But something goes wrong: TypeError: obj is undefined

Upvotes: 0

Views: 139

Answers (2)

rdiazv
rdiazv

Reputation: 1153

Actually, the allData function isn't necessary to do what you want. You could do something like this:

function checkIt (myobj){
    $.each(myobj.data(), function(key, value) {
        alert(key + "=" + value);
    });
}

myobj.data() will return an object with all the data assigned to the element.

Upvotes: 1

seliopou
seliopou

Reputation: 2916

When you call jQuery.data() on an element, it returns all the data attached to that element, so jQuery.fn.allData is redundant. Rewrite your checkIt function so it reads something like this:

function checkIt(myObj) {
  $.each($.data($(myObj)), function(key, value) {
    alert(key + "=" + value);
  })
}

Upvotes: 1

Related Questions