全球与Javascript中的局部变量 [英] Global & Local variables in Javascript
问题描述
我有一个变量和两个函数.两者都使用该变量.第一个函数是每次使用变量值时(全局)更改它.这是我想要的,但它对我不起作用.
I have one variable and two functions . The variable is used by both. and the first function is changing the variable value (globally) each time it's used by it . This is what I want but it is not working with me .
x = 1;
function f1()
{
x = x + 1;
// use x
}
function f2()
{
// use x
}
我读过其他线程,但是x始终为1,这非常令人沮丧:|
I've read other threads but x is always 1 which is very frustrating :|
添加:实际代码
<script type="text/javascript">
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
return (S4() + S4() + ";" + S4() + ";" + S4() + ";" + S4() + ";" + S4() + S4() + S4());
}
P = '';
function Save() {
P = guid();
$('#btnBrowse').uploadifyUpload();
}
$(document).ready(function () {
$('#txtText').elastic();
$('#btnBrowse').uploadify({
'uploader': '../uploadify.swf',
'script': '../uploadify.ashx',
'cancelImg': '/uploadify/cancel.png',
'folder': '../images/Albums/',
'multi': true,
'fileDesc': 'Web Image Files (.JPG, .GIF, .PNG)',
'fileExt': '*.jpg;*.gif;*.png',
'scriptData': { 'Album_ID': P },
'buttonText': 'Upload Images'
});
});
</script>
所以变量是P.并由jquery函数(uploadify)使用.每次我执行 保存功能我希望我得到变量P的新值.但是总是一样的?
so the variable is P . and it is used by jquery function (uploadify) . each time I excute Save function I expect I get a new value for variable P . But is always the same ??
推荐答案
问题是执行代码的时间时间. uplodify选项是在页面加载上设置的(包括P
在页面加载时传递),并且由于P
是字符串,因此以后(通过save()
)更改P
不会更改您传递的值.
The problem is the time when you execute the code. The uplodify options are set on page load (which includes that P
is passed on page load) and as P
is a string, changing P
later (through save()
) will not change the value you passed.
您可以通过传递对对象的引用作为选项来解决此问题,而不是字符串 无效.
该插件提供了 uploadifySettings
[docs] 方法来更改uploadify实例的设置.使用它来更新scriptData
设置:
The plugin provides a uploadifySettings
[docs] method to change the settings of an uploadify instance. Use it to update the scriptData
settings:
function Save() {
$('#btnBrowse').uploadifySettings('scriptData', {'Album_ID' : guid()}, true);
$('#btnBrowse').uploadifyUpload();
}
这篇关于全球与Javascript中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!