2012-03-31 65 views
0

如何在jQuery中使用click()以外的變量?我有以下的代碼 -使用click中指定的變量()

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

當我想用click()的attackValue之外它不會被定義。

回答

2

爲了保持功能的範圍之外定義attackValue,你需要聲明它點擊事件之外。

var attackValue; 

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

現在你應該可以在外面引用它了。

+0

如果OP在那裏聲明'attackValue'而沒有'var'關鍵字。它是全球性的,應該可以在功能之外訪問。儘管使用該代碼片段是不可能的。 – PeeHaa 2012-03-31 00:17:41

0

對於初學者來說:這是不是你應該如何在JavaScript中聲明一個變量:

attackValue = $(this).text(); 

這會弄亂「程序」可變空間。您應該始終使用關鍵字var在javascript中聲明變量。

當我想在click()之外使用attackValue時它不會被定義。

這取決於你想在何時何地使用它。考慮following code

var attackValue = 'some value'; 

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

console.log(attackvalue); // this would output some value, because the function hasn;t run yet 
setValue(); 

不過,如果你would do

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 

注意上面的代碼應該在closure運行。或者它仍會混亂變量空間(即使使用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 
})();