在子局部函数javascript中更改全局变量的值

时间:2015-03-29 02:43:12

标签: javascript variables global-variables

没有必要解释大部分代码。如您所见,全局变量cancel设置为true。然后调用一个函数,其中变量cancel被更改。 好像我可以访问第15,27或32行的cancel变量。 你能解释它为什么没有工作以及我如何解决它? 谢谢!请询问任何其他问题。我没有在这里解释其他代码,因为我认为它不直接与这个问题有关,如果我是这样的话,它会让这个问题读得太长。

1. var cancel = 'true';
2. function setSliders()
3. {
4.  var sliders = document.getElementsByClassName('slider');
5.  var sliderButtons = document.getElementsByClassName('sliderButton');
6.  for(var i = 0; i != sliderButtons.length; i++)
7.  {
8.      var slider = document.getElementsByClassName('sliderButton')[i];
9.      slider.onmousedown = function()
10.     {
11.         cancel = 'false';
12.         this.onmouseup = function(cancel)
13.         {
14.             cancel = 'true';
15.             alert(cancel +' within semi function cancel does not seem to be accessible here');
16.             //alert('test');
17.         };
18.         
19.         alert(cancel+' within function');
20.         
21.         this.onmousemove = function(event, cancel)
22.         {
23.             if(cancel == 'false')
24.             {
25.                 console.log('cancel is false'); //cancel doesn't seem to be accessible here either.
26.                 this.style.left = event.clientX+'px';
27.                 cancel = 'true';
28.             }
29.             else
30.             {
31.                 console.log('cancel is true'); //cancel isn't accessible here either.
32.                 cancel = 'false';
33.             }
34.         };
35.     };

1 个答案:

答案 0 :(得分:2)

您的函数的参数名称为cancel,这些函数中的cancel是该函数的本地函数。

如果从参数中删除cancel,它将引用全局cancel变量并应该有效。

1. var cancel = 'true';
2. function setSliders()
3. {
4.  var sliders = document.getElementsByClassName('slider');
5.  var sliderButtons = document.getElementsByClassName('sliderButton');
6.  for(var i = 0; i != sliderButtons.length; i++)
7.  {
8.      var slider = document.getElementsByClassName('sliderButton')[i];
9.      slider.onmousedown = function()
10.     {
11.         cancel = 'false';
12.         this.onmouseup = function()
13.         {
14.             cancel = 'true';
15.             alert(cancel +' within semi function cancel does not seem to be accessible here');
16.             //alert('test');
17.         };
18.         
19.         alert(cancel+' within function');
20.         
21.         this.onmousemove = function(event)
22.         {
23.             if(cancel == 'false')
24.             {
25.                 console.log('cancel is false'); //cancel doesn't seem to be accessible here either.
26.                 this.style.left = event.clientX+'px';
27.                 cancel = 'true';
28.             }
29.             else
30.             {
31.                 console.log('cancel is true'); //cancel isn't accessible here either.
32.                 cancel = 'false';
33.             }
34.         };
35.     };