用过滤器检查每个单词



我感觉像碰壁了。

我已经做了一个亵渎过滤器,然而这目前在输入一个坏词时工作,当输入更多的词(坏的或其他的)时,它不再过滤并提交良好。

我希望它不提交,如果有不好的词在输入中存在。

这是我目前为止写的内容:

var filterArray;
var inputArray;
$("button").on("click",function() {
    var input = $("input:text").val().toLowerCase();
    var inputArray = input.split(' ');
    console.log(inputArray);
    //for each item in inputArray
    $.each(inputArray, function() {
        if($.inArray(input, filterArray) !==-1)
        {
            console.log('Sorry you should not say ' + input + '!');
            return false;
        } else {
            console.log('passes');
        }
    });
});

$.ajax({
    async: false,
    url : "js/vendor/badwords.txt",
    dataType: "text",
    success : function (data) {
        filterArray = data.split(',');
    }
});

任何帮助都将是感激的,谢谢!

你需要从点击处理程序返回true/false,而不是你只是从each()回调方法返回。

$("button").on("click", function () {
    var input = $("input:text").val().toLowerCase();
    var inputArray = input.split(' ');
    console.log(inputArray);
    var valid = true;
    //for each item in inputArray
    $.each(inputArray, function (i, value) {
        //also need to use the current value in the inputArray
        if ($.inArray(value, filterArray) !== -1) {
            console.log('Sorry you should not say ' + value + '!');
            valid = false;
            //returning false from here stops the loop but don't prevent the default action of the button click
            return false;
        } else {
            console.log('passes');
        }
    });
    //return the valid state
    return valid;
});

演示:小提琴

if($.inArray(input, filterArray) !==-1)替换为if($.inArray($(this), filterArray) !==-1)。这将检查数组中的每个单词。目前,它只会多次查看第一个作品。

最新更新