hx-targethx-target 属性允许你将交换目标设为与发出 AJAX 请求的元素不同的元素。此属性的值可以是:
¥The hx-target attribute allows you to target a different element for swapping than the one issuing the AJAX
request. The value of this attribute can be:
要定位的元素的 CSS 查询选择器。
¥A CSS query selector of the element to target.
this 表示 hx-target 属性所在的元素是目标。
¥this which indicates that the element that the hx-target attribute is on is the target.
closest <CSS selector> 将查找与给定 CSS 选择器匹配的 closest 祖级元素或其自身(例如,closest tr 将定位元素最近的表格行)。
¥closest <CSS selector> which will find the closest
ancestor element or itself, that matches the given CSS selector
(e.g. closest tr will target the closest table row to the element).
find <CSS selector> 将查找与给定 CSS 选择器匹配的第一个子后代元素。
¥find <CSS selector> which will find the first child descendant element that matches the given CSS selector.
next 解析为 element.nextElementSibling
¥next which resolves to element.nextElementSibling
next <CSS selector> 将向前扫描 DOM 以查找与给定 CSS 选择器匹配的第一个元素。(例如 next .error 将定位到具有 error 类的最近的后续兄弟元素)
¥next <CSS selector> which will scan the DOM forward for the first element that matches the given CSS selector.
(e.g. next .error will target the closest following sibling element with error class)
previous 解析为 element.previousElementSibling
¥previous which resolves to element.previousElementSibling
previous <CSS selector> 将向后扫描 DOM 以查找与给定 CSS 选择器匹配的第一个元素。(例如 previous .error 将定位到具有 error 类的最近的前一个兄弟元素)
¥previous <CSS selector> which will scan the DOM backwards for the first element that matches the given CSS selector.
(e.g. previous .error will target the closest previous sibling with error class)
以下是针对 div 的示例:
¥Here is an example that targets a div:
<div>
<div id="response-div"></div>
<button hx-post="/register" hx-target="#response-div" hx-swap="beforeend">
Register!
</button>
</div>
来自 /register URL 的响应将附加到 ID 为 response-div 的 div。
¥The response from the /register url will be appended to the div with the id response-div.
此示例使用 hx-target="this" 创建一个在单击时自动更新的链接:
¥This example uses hx-target="this" to make a link that updates itself when clicked:
<a hx-post="/new-link" hx-target="this" hx-swap="outerHTML">New link</a>
¥Notes
hx-target 是继承的,可以放在父元素上
¥hx-target is inherited and can be placed on a parent element