hx-include
hx-include
属性允许你在 AJAX 请求中包含其他元素值。此属性的值可以是:
¥The hx-include
attribute allows you to include additional element values in an AJAX request. The value of this
attribute can be:
要包含的元素的 CSS 查询选择器。
¥A CSS query selector of the elements to include.
this
将包含元素的后代。
¥this
which will include the descendants of the element.
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 <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 <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)
以下是包含单独输入值的示例:
¥Here is an example that includes a separate input value:
<div>
<button hx-post="/register" hx-include="[name='email']">
Register!
</button>
Enter email: <input name="email" type="email"/>
</div>
这有点牵强,因为你通常会将这两个元素都放在 form
中并自动提交值,但它演示了这个概念。
¥This is a little contrived as you would typically enclose both of these elements in a form
and submit
the value automatically, but it demonstrates the concept.
请注意,如果你包含非输入元素,则将包含该元素中包含的所有输入元素。
¥Note that if you include a non-input element, all input elements enclosed in that element will be included.
¥Notes
hx-include
是继承的,可以放在父元素上
¥hx-include
is inherited and can be placed on a parent element
虽然 hx-include
是继承的,但它是从触发请求的元素中进行评估的。在使用扩展选择器(如 find
和 closest
)时很容易混淆。
¥While hx-include
is inherited, it is evaluated from the element triggering the request. It is easy to get confused
when working with the extended selectors such as find
and closest
.
<div hx-include="find input">
<button hx-post="/register">
Register!
</button>
Enter email: <input name="email" type="email"/>
</div>
在上面的例子中,单击按钮时,find input
选择器从按钮本身解析,这里不返回任何元素,因为按钮没有任何 input
子元素,因此在这种情况下会引发错误。
¥In the above example, when clicking on the button, the find input
selector is resolved from the button itself, which
does not return any element here, since the button doesn’t have any input
child, thus in this case, raises an error.
标准 CSS 选择器解析为 document.querySelectorAll 并将包含多个元素,而扩展选择器(如 find
或 next
)最多只返回一个要包含的元素
¥A standard CSS selector resolves
to document.querySelectorAll and will include
multiple elements, while the extended selectors such as find
or next
only return a single element at most to
include