开发者

How do I add key / value pairs to a global variable in JQuery?

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("da开发者_如何学编程ta-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?


It seems that $.scoreArray.labels is undefined when you try to access it.

Make sure it is defined before you try to add items to it.

As a side note, others are correct that if you're going to use named properties, you should use an object instead of an Array.

If you wanted an array of objects, do this:

$.scoreArray = {
    scores: [],
    labels: []
};
$(".word").each(function (i) {
    $.scoreArray.labels[ i ] = {};
    $.scoreArray.labels[ i ].label = $(this).attr("data-label");
    $.scoreArray.labels[ i ].x = $(this).attr("data-x");
}

or this:

$.scoreArray = {
    scores: [],
    labels: []
};
$(".word").each(function (i) {
    $.scoreArray.labels[ i ] = {label: $(this).attr("data-label"),
                                    x: $(this).attr("data-lx")
                               };
}

or perhaps an even better solution would be to use .map(). This (and the other solutions) assume you're not adding to an existing Array.

$.scoreArray.labels = $(".word").map(function (i) {
     return {label: $(this).attr("data-label"),
                 x: $(this).attr("data-lx")
            };
}).get();


It looks to me like you'd be better with an array of objects rather than an object with two arrays as it looks like a score should be kept tied with the label.

// are you sure you want to add this as a property on the jQuery object?
var $.scoreArray = $.map($('.word') , function(elem) { 
                       var self = $(elem);
                       return { score : self.attr("data-x"),
                                label : self.attr("data-label") };
                   });

// $.scoreArray will be an array of objects, each with a score and label property
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜