代码运行良好,但我需要它通过按下按键来启动搜索和过滤模型项目,并可能在过滤之前创建 1 秒的延迟。这是我的 html.erb 搜索片段
<%= search_form_for @query, url: users_path, data: {search_delay_target: "form"}, method: :get, html: { class: "relative" } do |f| %>
<div class="relative">
<%= f.search_field :first_name_or_last_name_or_email_cont, placeholder: "Search...", data: { action: 'keydown->search-delay#search', search_delay_target: "input"}, class:
"block w-full rounded-md border-0 pl-10 py-2 pr-12 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" %>
<div class="absolute inset-y-0 left-0 flex py-3.5 pl-3">
<svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-5.5-5.5M10 14a7 7 0 1 1 0-14 7 7 0 0 1 0 14z"/>
</svg>
</div>
<div class="absolute inset-y-0 right-0 flex py-1.5 pr-1.5">
<kbd class="inline-flex items-center rounded border border-gray-200 px-1 font-sans text-xs text-gray-400">⌘K</kbd>
</div>
</div>
<%= f.submit "Search", class: "hidden" %>
<% end %>
为了实现您需要编写javascript的功能。
searchField = document.getElementById('input-field')
searchField.addEventListener('input', function(event) => {
const query = event.target.value.trim();
// also use setTimeout if you want to have 1 second delay before search.
setTimeout(() => {
// search logic
}, 1000)
// write fetch logic here.
})