我正在尝试从头开始创建我自己的自动完成功能。下面的代码检查 result
类中的结果。然后 result
类中的值循环遍历 name
类。如果特定字符串匹配,则添加一个名为 display
我现在遇到的问题是类 display
只有在完全匹配而不是部分匹配时才会被添加(这意味着我必须完成整个字符串)。如果我尝试删除或删除 input textfield
中的值,它似乎不会删除当前添加的类
$('.name-box').on("input", function() {
let value = $(this).val();
let result = $(this).text(value);
$('.result').text(value);
// $(this).find('.name-' + val).addClass('display');
$('.name-list .name').each(function() {
if ($('.result').text() == $(this).text()) {
$(this).addClass('display');
} else if ($('.result').val() != $(this).val()) {
$(this).removeClass('display');
}
})
});
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input class="name-box" type="text" />
</form>
<ul class="name-list">
<li class="name name-noeldelacruz" data-bindhandle="@noeldelacruz">@noeldelacruz</li>
<li class="name name-john" data-bindhandle="@john">@john</li>
<li class="name name-joe" data-bindhandle="@joe">@joe</li>
<li class="name name-james" data-bindhandle="@james">@james</li>
<li class="name name-jake" data-bindhandle="@jake">@jake</li>
<li class="name name-jade" data-bindhandle="@jade">@jade</li>
</ul>
<div class="result"></div>
最佳答案
你可以像这样检查部分匹配:
if ($(this).text().includes($('.result').text())) {
$(this).addClass('display');
} else {
$(this).removeClass('display');
}
关于javascript - 使用 jquery 构建自动完成功能时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094788/