我无法弄清楚如何做到这一点。我正在使用jQuery,我知道inArray函数,但我被卡住了。当用户在输入字段中插入一些值时,我想检查输入的任何单词是否在数组中......如果他们要删除它们。这就是我所拥有的:
<input type="text" id="search"/>
$("#search").bind('enterKey', function(e){
var search = $('#search').val();
var check = ['on', 'a', 'the', 'of', 'in', 'if', 'an'];
var id = $.inArray(check, search);
if (id !== -1){
alert ("in array");
}else{
alert ("not in array");
}
});
$('#search').keyup(function(e){
if(e.keyCode == 13){
$(this).trigger("enterKey");
}
});
我确定我的if语句是错的......请帮帮我!
答案 0 :(得分:1)
您切换了检查并在inArray参数中搜索。检查api,它表示使用inArray(value, array)
(不是数组,值)。
答案 1 :(得分:1)
不是搜索数组中的单词,而是创建一个正则表达式来替换它们:
$("#search").bind('enterKey', function(e){
var search = $('#search').val(),
check = ['on', 'a', 'the', 'of', 'in', 'if', 'an'],
regexp = new RegExp( '\\b' + check.join( '\\b|\\b' ) + '\\b', 'ig' );
alert( search.replace( regexp, '' ) );
});
$('#search').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});