Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 使用click()中指定的变量_Jquery_Click - Fatal编程技术网

Jquery 使用click()中指定的变量

Jquery 使用click()中指定的变量,jquery,click,Jquery,Click,如何在jQuery中的click()之外使用变量?我有以下代码- $(".area").not(".enemy").click(function(){ $(".area").removeClass("clicked"); $(this).toggleClass("clicked"); attackValue = $(this).text(); }); 当我想在c

如何在
jQuery
中的
click()
之外使用变量?我有以下代码-

$(".area").not(".enemy").click(function(){
                $(".area").removeClass("clicked");
                $(this).toggleClass("clicked");
                attackValue = $(this).text();           
        });

当我想在
click()之外使用attackValue时,将不会定义它。

对于初学者:这不是在javascript中声明变量的方式:

attackValue = $(this).text();
这会使“程序”变量空间变得混乱。您应该使用
var
关键字在javascript中“始终”声明一个变量

当我想在click()之外使用attackValue时,它将不会被定义

这取决于你想在何时何地使用它。考虑:

但是,如果您:

请注意,上面的代码应该在一个数据库中运行。或者它仍然会使变量空间混乱(即使使用
var
)关键字。所以它看起来更像:

(function() { // yay closure, now all variables defined in here will stay in here
    var attackValue = 'some value';

    function setValue() {
      attackValue = 'some other value';
    }

    setValue();    

    console.log(attackValue); // this would output some other value, because the function did already run
})();

为了将定义的attackValue保持在函数范围之外,您需要在click事件之外声明它

var attackValue;

$(".area").not(".enemy").click(function(){ ... });

现在,您应该能够在外部引用它。

如果OP在那里声明
attackValue
,而不使用
var
关键字。它是全局的,应该可以在功能之外访问。尽管使用那个代码片段是不可能判断的。
(function() { // yay closure, now all variables defined in here will stay in here
    var attackValue = 'some value';

    function setValue() {
      attackValue = 'some other value';
    }

    setValue();    

    console.log(attackValue); // this would output some other value, because the function did already run
})();
var attackValue;

$(".area").not(".enemy").click(function(){ ... });