0

我觉得我要撞到一堵砖墙了。

我已经做了一个亵渎过滤器,但是当输入一个坏词时,这目前有效,当输入更多词(坏词或其他词)时,它不再过滤并提交正常。

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

这是我到目前为止所写的:

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(',');

    }
});

任何帮助将不胜感激,谢谢!

4

2 回答 2

2

您需要从单击处理程序返回 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;
});

演示:小提琴

于 2014-08-07T04:11:07.467 回答
0

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

于 2014-08-07T04:09:53.833 回答