Reputation: 10696
How can I get a var value from another function?
jQuery:
$(document).ready(function() {
function GetBiggestValue() {
var value = 0;
$('#tagCloud li a').each(function() {
if (value < $(this).attr('value')) {
value = $(this).attr('value');
}
});
var FullValue = value;
}
function Abc(){
console.log(FullValue);
}
Abc();
});
HTML:
<ul id="tagCloud">
<li><a href="#" value="1">Val 1</a></li>
<li><a href="#" value="2">Val 2</a></li>
<li><a href="#" value="3">Val 3</a></li>
<li><a href="#" value="4">Val 4</a></li>
</ul>
Upvotes: 0
Views: 6494
Reputation: 6999
declare outside the function
var value = 0;
$(document).ready(function() {
function GetBiggestValue() {
value = 0;
$('#tagCloud li a').each(function() {
if (value < $(this).attr('value')) {
value = $(this).attr('value');
}
});
}
function Abc(){
console.log(value);
}
Abc();
});
or return value
Upvotes: -1
Reputation: 2227
May be you want to use this value anywhere. So call GetBiggestValue() function and assign it a variable.
function GetBiggestValue() {
var value = 0;
$('#tagCloud li a').each(function() {
if (value < $(this).attr('value')) {
value = $(this).attr('value');
}
});
return value;
}
var FullValue = GetBiggestValue();
function Abc(){
console.log(FullValue);
}
Upvotes: 1
Reputation: 35793
Just return the value from the GetBiggestValue function:
function GetBiggestValue() {
var value = 0;
$('#tagCloud li a').each(function() {
if (value < $(this).attr('value')) {
value = $(this).attr('value');
}
});
return value;
}
function Abc(){
console.log(GetBiggestValue());
}
Upvotes: 0
Reputation: 83622
You cannot access variables from other contexts than your own or one of the parent contexts. The FullValue
variable is private to the GetBiggestValue()
function because you used the var
statement to define the variable. The correct procedure in your case would be to return value
from the GetBiggestValue()
function (although one might come up with another solution using a variable outside GetBiggestValue()
to store the value).
$(document).ready(function() {
function GetBiggestValue() {
var value = 0;
$('#tagCloud li a').each(function() {
if (value < $(this).attr('value')) {
value = $(this).attr('value');
}
});
return value;
}
function Abc(){
console.log(GetBiggestValue());
}
Abc();
});
Upvotes: 3