我正在尝试构建一个类似于自动完成字段工作方式的过滤功能。我正在使用Underscore.js来过滤一系列名称。这是一个演示问题的JSFiddle:
对于那些不想跳转到JSFiddle的人来说,这是纯文本中的例子。
HTML:
<p>Type the name 'Craig' into the text field</p>
<input class="query" type="text" />
<p>There are 4 Craig's in the data array. The results below should output those 4 Craigs. For some reason, it only outputs two.</p>
<p>Results:</p>
<textarea class="results" style="width: 300px; height: 300px;"></textarea>
JavaScript的:
var data = ["Aaron Abram", "Abbie Hanson", "Abraham Vázquez", "Ace Marrero", "Adam D. Chaitin", "Adam Duzey", "Adam Reichental", "Adam Scott", "Adam Smythe", "Addison McCaleb", "Ahmad Childress", "Aidas Petrulis", "Aldo Nievas", "Alex Alexapolsky", "Alexander R. Lampone", "Alexandra Elizabeth London", "Alexandra Jacobs", "Alexis Jones", "Allan Louis", "Allie Tintle", "Alyssa Wada", "Amanda Armstrong", "Amanda Olmstead", "Amber Fox", "Amber Graves", "Amy Berkin-Chavez", "Amy Buggy", "Amy Rush", "Amy Schlumberger", "Andi Dzilums", "Andre Savage", "Andrew Fryer", "Andrew Rivetty", "Angel Chavez", "Angel Lewis", "Angela Truong", "Anthony Wentzel", "Anya Estrov", "Aram Homampour", "Ariana Blumenfeld-James", "Armo Movsessian", "Ashley DeMeza", "Ashley Froschauer", "Athena Asklipiadis", "Athena Stamos", "Audryn Swigert", "Augie Sanchez", "Avi Horn", "Bali Ciri Yoman", "Bali Distinction Norman", "Barnaby Hitzig", "Betty Tran Chillino", "Bill McGovern", "Blues Bob", "Bob Cribbs", "Bob West", "Bobby DiGiacomo", "Borivoj Ivanovic", "Brad Horwitz", "Brad Ormand", "Bradley F. Cole", "Brandon Jordan", "Brandon Kosoko", "Brent Nelson", "Brett Vadset", "Brian Kubat", "Bridget Betts", "Brock Winberg", "Bryan C Dickson", "Caleb Bacon", "Carlos Carreras", "Carlos Castro", "Carlos Chávez", "Caryn Saxena", "Celina Chavanette", "Ceren Güven", "Chad Buechler", "Charles Winemiller", "Charlie Diaz", "Cheri Kingsley", "Chloe Sherman-Pepe", "Chris Hackett", "Chris Han", "Chris Laughter", "Chris Mabli", "Chris McGarry", "Chris Scott", "Chris Ueland", "Christelle Penalosa", "Christine Is Lovely", "Clark McCutchen", "Colleen Steckloff Mayo", "Cory J Thomas", "Craig Adams", "Craig Duro", "Craig Fredrics", "Craig Phelps", "Curt Bonnem", "Dalilah Rain", "Damien Nemire-Pepe"];
_.each(data, function (name) {
$('textarea.results').val($('textarea.results').val() + name + "\n");
});
$('input.query').bind('input', function (event) {
var pattern = new RegExp($(event.currentTarget).val(), 'gim'),
filteredResults = _.filter(data, function (name) {
return pattern.test(name)
});
$('textarea.results').val('');
_.each(filteredResults, function (name) {
$('textarea.results').val($('textarea.results').val() + name + "\n");
});
});
我得到了一些结果,而不是所有应该回来的结果。
知道我做错了吗?
答案 0 :(得分:1)
如果你可以从RegExp中删除全局标志,这应该可行。
var pattern = new RegExp($(event.currentTarget).val(), 'im');