Reputation: 1008
I'm trying to pass an argument through an .each
function, but can't seem to do so. Yet, before the .each
statement, the argument has a value, but I can't get to it from within said statement.
show: function (new_value) {
console.log( new_value ) // returns proper information
$('span[data-xyz]').each(function () {
console.log( new_value ) // returns `undefinded`
var attribute = $(this).attr("data-xyz");
if(typeof new_value === "undefined")
var new_value = system.defaults.xyz;
console.log( new_value ) // returns `system.defaults.xyz`
$(this).text(attribute[new_value]);
}
}
How can I get new_value
to be received in my .each
statement ?
Upvotes: 1
Views: 1567
Reputation: 817238
This line
var new_value = system.defaults.xyz
declares a local variable inside the the each
callback. The variable doesn't have a value until this line is executed, that's why you get undefined
.
If you don't want to declare a new variable, but rather reference the new_value
variable from the outer function, drop the var
keyword.
Learn more about hoisting.
Upvotes: 2