使用javascript进行搜索时,重点放在搜索词上

时间:2018-06-21 09:35:52

标签: javascript php arrays json search

抱歉,如果很难理解。我必须创建一些代码来关注我们想要搜索的单词。我给你例子

  1. 请说一下,当我们进入页面时。该复选框来自数据库表“ drinks”

enter image description here

  1. 然后当我在搜索区域中插入单词时。它将聚焦并消除该复选框

enter image description here

  1. 当我选择其中一些时

enter image description here

,然后按重置键。它将显示所有复选框,但所选的复选框不会消失。

enter image description here

是否有示例代码?

2 个答案:

答案 0 :(得分:1)

为此,我可以想到2种解决方案:

1。)使用自动完成功能,并在自动完成选项中包含复选框。您必须修改该复选框并将其包括在选项中。 This question可以帮助您。

2。)将其转换为标签系统,即删除复选框,并在选择任何选项时将其显示为标签。这样,您可以轻松添加/删除选项。为此,您可以使用Select2。引用链接中的“ multiple”选项,您将得到我所指的内容。

希望这会有所帮助。

答案 1 :(得分:0)

有很多方法可以实现您想要的。

这里是一个示例,该示例查看每个复选框的文本,并将其隐藏或显示。按reset只会清空搜索框,然后再次按搜索按钮。

事件侦听器只是侦听按钮按下的一种方式,然后dispatchEvent只是在伪造按钮按下。

如果有任何令人困惑的地方,请随时询问。

const popSearch = document.querySelector('.pop_search');
const popSearchInput = popSearch.querySelector('.input');
const popSearchSearch = popSearch.querySelector('.search');
const popSearchReset = popSearch.querySelector('.reset');
const filterList = document.querySelector('.filter_list');

popSearchSearch.addEventListener('click', () => {
  for (let item of filterList.querySelectorAll('li')) {
    if (item.textContent.includes(popSearchInput.value)) {
      item.removeAttribute('hidden')
    } else {
      item.setAttribute('hidden', '')
    }
  }
});

popSearchReset.addEventListener('click', () => {
  popSearchInput.value = "";
  popSearchSearch.dispatchEvent(new Event('click'))
});
ul.filter_list {
  list-style-type: none;
}
<p class="pop_search">
  <input class="input" placeholder="Search" />
  <button class="search">Search</button>
  <button class="reset">Reset</button>
</p>

<ul class="filter_list">
  <li><label><input type="checkbox" />ice tea</label></li>
  <li><label><input type="checkbox" />ice lemon tea</label></li>
  <li><label><input type="checkbox" />ice coffee</label></li>
  <li><label><input type="checkbox" />bubble tea</label></li>
  <li><label><input type="checkbox" />milk tea</label></li>
  <li><label><input type="checkbox" />hot chocolate</label></li>
  <li><label><input type="checkbox" />ice chocolate</label></li>
</ul>

希望您对此有帮助

相关问题