0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.