【问题标题】:Inserting autocomplete HTML suggestions into the search bar在搜索栏中插入自动完成 HTML 建议
【发布时间】:2020-01-20 17:35:09
【问题描述】:

自动完成脚本:

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
let states;

// Get states
const getStates = async () => {
 const res = await fetch('../complete/data/pictures.json');
 states = await res.json();
};

// FIlter states
const searchStates = searchText => {
 // Get matches to current text input
 let matches = states.filter(state => {
  const regex = new RegExp(`^${searchText}`, 'gi');
  return state.title.match(regex);
 });

 // Clear when input or matches are empty
 if (searchText.length === 0) {
  matches = [];
  matchList.innerHTML = '';
 }

 outputHtml(matches);
};

// Show results in HTML
const outputHtml = matches => {
 if (matches.length > 0) {
  const html = matches
   .map(
    match => `<div class="card card-body mb-1">
    <h4>${match.title}</h4>
   </div>`
   )
   .join('');
  matchList.innerHTML = html;
 }
};
window.addEventListener('DOMContentLoaded', getStates);
search.addEventListener('input', () => searchStates(search.value));

上面的代码会生成自动完成的 HTML 建议。我想添加可点击的功能,将点击的 html 元素插入到搜索栏中。

我得到的最接近的是:

matchList.addEventListener('click', () => {search.value = matchList.textContent.trim()})

如果只有一个建议,这可行,但如果有更多建议,则将所有建议插入在一起。

问题似乎在于matchList 是一个返回单个HTML 元素的对象。 如何返回一个可以迭代的对象并在该对象内的每个 HTML 建议上放置一个 onclick

或者,我如何返回多个对象,每个对象都包含一个 HTML 建议,然后我可以在上面放置 onclick

或者第三个选项?

【问题讨论】:

    标签: javascript html ajax autocomplete


    【解决方案1】:
    matchList.addEventListener('click', e => search.value = e.target.textContent.trim())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 2014-03-20
      • 2021-01-27
      • 2017-10-22
      • 2017-02-22
      • 1970-01-01
      相关资源
      最近更新 更多