javascript - 为另一个函数保留 JQuery 变量(全局变量?)

标签 javascript jquery arrays passwords

我正在尝试制作一个密码检查系统。 我决定还想检查一下它是否是常用密码。

为此,我将外部 txt 文件加载到数组中。但是,我的密码检查功能似乎无法读取该数组。

jQuery(document).ready(function() {
var commonPass = new Array;
jQuery.get('/static/commonPass.txt', function(data){
    commonPass = data.split('\n');
    console.log(commonPass);
});
console.log(commonPass);
//you have to use keyup, because keydown will not catch the currently entered value
jQuery('input[type=password]').keyup(function() { 

    // set password variable
    var pswd = jQuery(this).val();

    //check if common password
    console.log(pswd);
    if ( jQuery.inArray(str.toLowerCase(pswd), commonPass)!= -1) {
        console.log('InArray');
        jQuery('#known').removeClass('valid').addClass('invalid');
    } else {
        console.log('NotInArray');
        jQuery('#known').removeClass('invalid').addClass('valid');
    }

});

是否可以创建全局 jQuery/Javascript 变量,这可以解决此问题吗?

最佳答案

commonPass 移出所有函数的范围

jQuery(document).ready(function() {
var commonPass = new Array;

...应该是...

var commonPass = new Array;
jQuery(document).ready(function() {

或者您可以使用window.commonPasswindow 是 JavaScript 在浏览器中工作时的“全局”变量。 Javascript 的变量存在于它们所声明的函数的作用域内(如果在函数外部,则存在于 window 范围内)。

关于javascript - 为另一个函数保留 JQuery 变量(全局变量?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29041216/

相关文章:

javascript - 如何在javascript中搜索列表中的元素?

javascript - 动态设置/更改事件处理程序是不好的做法吗?

Javascript 与 before() 和 after() 的混淆

javascript - 如何循环遍历 100 个具有不同属性的对象的数组并从每个对象中检索 1 个属性值?

javascript - 在 chrome 和 mozilla 中用 relative 和 grid 显示不同的元素值

javascript - 类型错误 : Cannot read property 'add' of undefined Discord. js javascript

javascript - 隐藏文件扩展名

javascript - 将动态表转换为数组

javascript - 下划线返回数组中对象的索引,其中单词存在于对象内的句子中

javascript: getAverageAge 所有对象