如何解决htmx:e.querySelectorAll 不是函数
如果我使用 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
}
<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>')
更新 2
嗯,现在我知道为什么会失败了:
parseFromString()
的 Chrome 是根本原因:
更新 3
后续问题:Make parseFromString() parse without validation
更新 4
我创建了一个问题,希望有更多创意的人知道如何解决这个问题:https://github.com/bigskysoftware/htmx/issues/469
解决方法
我创建了一个 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 能够处理原始字符串,那就太好了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。