我得到了这个
$('#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>
答案 0 :(得分: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
答案 1 :(得分:1)
更改:强>
var authCode = $.sha1(toSha1);
以强>
window.authCode = $.sha1(toSha1);