我明白了
$('#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>
最佳答案
显式使其成为全局:
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
关于javascript - 使 javascript 变量在整个脚本中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747324/