I have a function like so:
var eatLunch = (function () {
var sandwiches = [$("#sand1"), $("#sand2")];
return function (eaten) {
for (var i = 0, len = eaten.length; i < len; i++) {
sandwiches[i].attr("class", "eaten-by " + eaten[i].by)
}
};
}());
eatLunch([
{
result: "good",
by: "Adam"
},
{
result: "meh",
by: "Adam"
}
]);
The intention is to cache the dom elements #sand1 and #sand2 in a closure to reduce the number of dom touches this function has to make. Without closure, the elements have to be assigned to variables every time I call the function.
However, the attr method does not seem to work. Upon further inspection, sandwiches[i] is defined, and it has the attr method. The function does not throw an error, it just keeps looping, but the dom elements do not get updated.
If I move sandwiches into the local scope, it works perfectly, but this is more expensive. See below:
var eatLunch = function (eaten) {
var sandwiches = [$("sand1"), $("sand2")];
for (var i = 0, len = eaten.length; i < len; i++) {
sandwiches[i].attr("class", "eaten-by " + eaten[i].by)
}
};
eatLunch([
{
result: "good",
by: "Adam"
},
{
result: "meh",
by: 开发者_开发百科"Adam"
}
]);
What's going on here?
You're probably running your code before the DOM is loaded.
Move it to the bottom of the page.
var i = 0, var len = eaten.length;
Don't use var
in the second one. Write:
var i = 0, len = eaten.length;
You also need to change eaten.by
to eaten[i].by
Minor errors are a pain to find.
Live Fixed Example
精彩评论