How to get value from outside of the function in javascript?
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>
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();
});
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);
}
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());
}
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
精彩评论