2012-01-05 32 views
0

我得到這個使JavaScript變量可見在整個腳本

$('#password').change(function() { 
    var toSha1 = $('#msisdn').val() + $('#password').val(); 
    var authCode = $.sha1(toSha1); 
}); 

我怎樣才能把這些變量AUTHCODE在整個腳本可見。例如這個工作正常:

$('#password').change(function() { 
    var toSha1 = $('#msisdn').val() + $('#password').val(); 
    var authCode = $.sha1(toSha1); 
}); 
alert(authCode); 

我試過了,沒有關鍵字「var」,但它似乎不工作。

編輯:這裏的源

<div data-role="content"> 
    <textarea id='resultArea'></textarea> 
    <label for='msisdn'>MSISDN:</label> 
    <input type='text' id='msisdn' value='+359899888777'> 
    <label for='authCode'>authCode:</label> 
    <input type='text' id='authCode' value='8bcac5dabf06219843a5a3b755c47e69600e050a'> 
    <label for='password'>Password:</label> 
    <input type='password' id='password' value='123'> 
    <button data-role='button' data-inline='true' data-theme='e' id='register'>Register</button> 
    <button data-role='button' data-inline='true' data-theme='e' id='login'>Login</button> 
</div><!-- /content --> 
<script> 
$('#resultArea').hide(); 
$('#password').change(function() { 
    var toSha1 = $('#msisdn').val() + $('#password').val(); 
    window.authCode = $.sha1(toSha1); 
}); 
alert(window.authCode); 
</script> 

回答

3

使之成爲全球性明確:

window.authCode = $.sha1(toSha1); 

全局變量是window對象的屬性。

請注意,您的代碼存在單獨的問題:您在連接處理程序後立即提醒authCode的值,而不是在change事件觸發時提醒值。查看評論:

$('#resultArea').hide();    // Happens immediately 
$('#password').change(function() {  // change() call happens immediately, setting up the handler 
    // ...but this code runs when the handler is *called*, not inline with the code above and below 
    var toSha1 = $('#msisdn').val() + $('#password').val(); 
    window.authCode = $.sha1(toSha1); 
}); 
alert(window.authCode);    // Happens immediately after the calls above 
+0

確定我使用window.authCode insted的VAR AUTHCODE和AUTHCODE的,但是當我使用alert(authCode)沒有任何反應,當你唱警報(window.authCode)它打印「未定義」。看看我對源 – user1113314 2012-01-05 18:17:04

+0

@ user1113314的第一條評論:這是因爲你的'alert'發生在'change'事件被觸發之前。 – 2012-01-05 18:26:55

+0

非常感謝!我完全理解它:) – user1113314 2012-01-05 18:45:53

1

變化:

var authCode = $.sha1(toSha1);

window.authCode = $.sha1(toSha1);