我正在尝试构建一个过滤功能,其工作方式类似于自动完成字段的工作方式。我正在使用 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");
});
});
我得到了一些结果,而不是所有应该回来的结果。
知道我做错了什么吗?