此示例展示了如何使用 htmx 加载选项卡内容,以及如何使用 Javascript 选择 “active” 选项卡。这通过将重新渲染选项卡 HTML 的部分工作从应用服务器转移到客户端浏览器来减少一些重复。
¥This example shows how to load tab contents using htmx, and to select the “active” tab using Javascript. This reduces some duplication by offloading some of the work of re-rendering the tab HTML from your application server to your clients’ browsers.
你还可以考虑遵循 超文本作为应用状态的引擎 原则的 更惯用的方法。
¥You may also consider a more idiomatic approach that follows the principle of Hypertext As The Engine Of Application State.
¥Example Code
下面的 HTML 显示选项卡列表,并添加了 HTMX 以从服务器动态加载每个选项卡窗格。当内容交换到 DOM 中时,简单的 JavaScript 事件处理程序使用 take
函数 切换选定的选项卡。
¥The HTML below displays a list of tabs, with added HTMX to dynamically load each tab pane from the server. A simple
JavaScript event handler uses the take
function to switch the selected tab
when the content is swapped into the DOM.
<div id="tabs" hx-target="#tab-contents" role="tablist"
hx-on:htmx-after-on-load="let currentTab = document.querySelector('[aria-selected=true]');
currentTab.setAttribute('aria-selected', 'false')
currentTab.classList.remove('selected')
let newTab = event.target
newTab.setAttribute('aria-selected', 'true')
newTab.classList.add('selected')">
<button role="tab" aria-controls="tab-contents" aria-selected="true" hx-get="/tab1" class="selected">Tab 1</button>
<button role="tab" aria-controls="tab-contents" aria-selected="false" hx-get="/tab2">Tab 2</button>
<button role="tab" aria-controls="tab-contents" aria-selected="false" hx-get="/tab3">Tab 3</button>
</div>
<div id="tab-contents" role="tabpanel" hx-get="/tab1" hx-trigger="load"></div>