I've got a program that add's a bunch of Div's to a page. I have a bunch of extra 'data-' attributes added to the divs that I later want to include in a global variable.
I basically want to set something up like this:
$.scoreArray = {
scores: [],
labels: []
};
$(".word").each(function (i) {
$.scoreArray.labels.label = $(this).attr("data-label");
$.scoreArray.labels.x = $(this).attr("data-x");
}
...
but I keep getting the error TypeError: Cannot set property 'label' of undefined
I've tried putting .label and .x as ["label"] and ["x"] but to no avail. What am I doing wrong?
Edited: I think I see what you want to do. You want the arrays to contain a bunch of objects, one for each word, which contain the attributes you're collecting. So you want something like:
$.scoreArray = {
scores: [],
labels: []
};
$(".word").each(function (i) {
newLabel = {};
newLabel.label = $(this).attr("data-label");
newLabel.x = $(this).attr("data-x");
$.scoreArray.labels.push(newLabel);
}
However, the error you're seeing sounds like the "global" variable you created isn't being found in the scope you're in. Is this your actual code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With