weixin_33736649 2014-08-07 04:06 采纳率: 0%
浏览 35

遍历过滤器中的每个单词

I feel like i'm coming up against a brick wall.

I've made a profanity filter, however this currently works when one bad word is entered, when more words (bad or otherwise) are entered it no longer filters and submits fine.

I'd like it to not submit if there are bad words present inside the input.

Here's what i've written so far:

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

    }
});

Any help would be appreciated, thank you!

  • 写回答

2条回答 默认 最新

  • weixin_33724059 2014-08-07 04:09
    关注

    Replace if($.inArray(input, filterArray) !==-1) with if($.inArray($(this), filterArray) !==-1). This should check every word in the array. Currently, it only looks at the first work multiple times.

    评论
  • weixin_33724059 2014-08-07 04:11
    关注

    you need to return true/false from the click handler instead you are just returning from the each() callback method.

    $("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;
    });
    

    Demo: Fiddle

    评论

报告相同问题?

悬赏问题

  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信
  • ¥15 使用QT实现can通信