如果我使用hx-swap-oob,那么我会得到一个错误:
<script src="https://unpkg.com/htmx.org@1.3.3/dist/htmx.js"></script>
<div id="sum">?</div>
<table>
<tr>
<td><button
hx-get="https://run.mocky.io/v3/b5a6902e-fc46-479b-92e4-9b4befc7a920"
hx-target="closest tr">1</button>
</td>
<td>one</td>
</tr>
</table>
按“运行代码片段”,然后按1
htmx:swapError
{
"message": "e.querySelectorAll is not a function",
"filename": undefined,
"lineno": undefined,
"colno": undefined
}mocky http endpoint返回以下内容:
<tr>
<td>2</td><td>two</td>
</tr>
<div id="sum" hx-swap-oob="true">MAGIC</div>在上面的示例中,我使用了非最小化版本,因此错误消息是:eltOrSelector.querySelectorAll is not a function
如果我使用这个端点,它不会失败:https://run.mocky.io/v3/2ab904eb-23a9-4006-b68b-f112b55841f3
但在我的用例中,新的html片段应该是<tr>...</tr>,而不是<div>.
JS堆栈跟踪:
Uncaught TypeError: eltOrSelector.querySelectorAll is not a function
at findAll (htmx.js:295)
at handleOutOfBandSwaps (htmx.js:501)
at selectAndSwap (htmx.js:712)
at doSwap (htmx.js:2284)
at handleAjaxResponse (htmx.js:2358)
at XMLHttpRequest.xhr.onload (htmx.js:2163)更新
我可以将问题的范围缩小到以下范围:

这将失败:
makeFragment('<tr><td>a</td></tr> <div>X</div>')Update2
嗯,现在我知道为什么它失败了:

Chrome的parseFromString()是根本原因:

Update3
后续问题:Make parseFromString() parse without validation
Update4
我创建了一个问题,希望有更有创造力的人有办法解决这个问题:https://github.com/bigskysoftware/htmx/issues/469
发布于 2021-04-29 19:00:41
我创建了一个new endpoint,它返回一个稍微不同的HTML片段:
<table>
<tr id="row1">
<td>2</td><td>two</td>
</tr>
</table>
<div id="sum" hx-swap-oob="true">MAGIC</div>
<script src="https://unpkg.com/htmx.org@1.3.3/dist/htmx.js"></script>
<div id="sum">?</div>
before table
<table>
<tr id="row1">
<td><button
hx-get="https://run.mocky.io/v3/28a8e653-491c-4186-abd4-4f48f3579273"
hx-target="#row1" hx-select="#row1">1</button>
</td>
<td>one</td>
</tr>
</table>
after table
HTMX在内部使用parseFromString(),此方法验证输入。如果存在无效的HTML,它可能会截断元素。
HTMX的makeFragment()包装它发送给parseFromString()的字符串。HTMX查看响应中的第一个元素。在上面的问题中,它是<tr>。因此,htmx使用<table>来包装整个http响应。

解决方案是将一个“正常”元素返回给htmx (而不是<tr>)。
htmx中的普通html片段恰好是一个元素,所以这无关紧要。如果使用hx-swap-oob,服务器会向客户端发送几个元素。
这或多或少是一种变通方法。如果htmx可以处理原始字符串,那就太好了。
https://stackoverflow.com/questions/67289814
复制相似问题