因此,我尝试了一下 HTMX,并设计了一个小型应用程序,该应用程序可以聚合来自不同来源的新闻文章并在单个提要上显示它们。
对于这个提要,我想进行高级搜索,其中包括:
我想在以下事件上触发整个搜索:
为此,我使用了带有嵌套
<form>
、<input>
和 <select>
元素的 <button>
:
<div id="articles-search">
<form id="search-form"
hx-get="/"
hx-target="#articles-search"
hx-swap="innerHTML"
hx-vals="{search: document.getElementById('search').value, source: document.getElementById('source').value}"
hx-trigger="keyup delay:500ms, change">
<label for="search">Search</label>
<input type="search" id="search"
name="search" placeholder="Type here.."
{% if existing_search %}value="{{ existing_search }}"{% endif %}/>
<label for="source">Source</label>
<select name="source" id="source">
<option value="">All</option>
{% for source in sources %}
<option value="{{ source.value }}"
{% if selected_source == source.value %}selected{% endif %}>
{{ source.value }}
</option>
{% endfor %}
</select>
<button type="submit">Search</button>
</form>
<div id="search-results">
{% if articles %}
<hr>
{% for article in articles %}
<h2>{{ article.title }}</h2>
<p>{{ article.source.value }}</p>
<p>{{ article.description }}</p>
<p><a href="{{ article.url }}" target="_blank">Read more</a></p>
<hr/>
{% endfor %}
{% endif %}
</div>
</div>
这是文档的一部分,仅在提供
HX-Request
标头时才会呈现。我正在使用 jinja2 库在 Python 中渲染 HTML 模板。
通过此设置,一切都按我的预期工作,除了当通过
keyup
或 change
事件提交表单时,它不会将 search
和 source
值放入查询参数列表。我想将它们放在 URL 中,这样您就可以复制 URL 并与其他人共享,其他人会看到应用了相同的搜索。
但是,当使用提交按钮提交表单或在搜索时按 ENTER 键时,它会将表单值放入查询参数中。
我的问题是:
hx-trigger
事件上将表单值放入查询参数?<div>
中?可以将 <div>
用作 <form>
吗?它如何影响网站抓取者?我尝试使用
hx-vals
来达到此目的,但这似乎没有效果。
另外,Copilot Chat 建议我放置下一个脚本:
document.addEventListener('DOMContentLoaded', function() {
var searchForm = document.getElementById('search-form');
var searchInput = document.getElementById('search');
var sourceInput = document.getElementById('source');
function updateHxVals() {
searchForm.setAttribute('hx-vals', JSON.stringify({
search: searchInput.value,
source: sourceInput.value
}));
}
searchInput.addEventListener('keyup', updateHxVals);
sourceInput.addEventListener('change', updateHxVals);
});
但这也没有解决问题
您可以使用
from:
选择器从特定元素触发事件。您还可以将其与逗号分隔的事件结合起来,以获取表单中所有不同类型的事件。它也应该允许您保留所有值。
在你的情况下,这样的东西应该有效:
hx-trigger="submit, input changed delay:500ms from:input, search, change from:select"