如何使用 htmx 更新两个目标?

huangapple go评论44阅读模式
英文:

How to update 2 target with htmx?

问题

我有以下的 htmx 代码

<button
        hx-get="/views/users/byId/someId"
        hx-target=".details">Details</button>
<div class="details">first</div>
<div class="details">second</div>

这只改变第一个 div,第二个 div 不会改变。
我想要更新底部具有相同类名的两个 div。
怎么做呢?

我还尝试了多个 div,但由于我们不能有多个 div,所以出现错误。

英文:

I have following htmx code

<button
        hx-get="/views/users/byId/someId"
        hx-target=".details">Details</button>
<div class="details">first</div>
<div class="details">second</div>

This only change first div and second div does not change
I want to update both div in the bottom with same class name
How to do this this?

I also tried multiple div but as we cant have multiple div that was giving error

答案1

得分: 5

文档中关于hx-target的说明指出,像hx-get和hx-post这样的事务只会替换匹配条件的页面上的第一个DOM节点。无论您是使用默认操作(替换当前的DOM节点)还是指定自己的CSS选择器,都是如此。

这对于htmx来说是一个相当常见的问题,在网站上有一个多种不同方法来完成这个任务的示例。这个示例列出了三种可能的解决方案:

  1. 使用hx-target来替换页面的一个较大部分。
  2. 使用Out of Band Swaps
  3. 使用自定义事件和hx-trigger来触发在初始交换之后执行的其他交换。

在不查看您的用例的其余部分的情况下很难确定“正确”的答案。但我猜您可以扩展您的目标区域,然后就可以了。

英文:

The documentation for hx-target says that transactions like hx-get and hx-post will only replace the first DOM node on the page that matches the criteria. This is true whether you're using the default action (which swaps out the current DOM node) or specifying your own CSS selector.

This is a pretty common question for htmx, and there's an example of several different ways to accomplish this on the website. This example lists three possible solutions:

  1. Use hx-target to swap a larger portion of the page.
  2. Use Out of Band Swaps
  3. Use custom events and hx-trigger to trigger additional swaps that follow after the initial one.

It's hard to say what's the "right" answer without looking at the rest of your use case. But my guess is that you could just expand the area you're targeting and call it a day.

<div id="swap-all-this">
    <button
        hx-get="/views/users/byId/someId"
        hx-target="#swap-all-this">Details</button>
    <div class="details">first</div>
    <div class="details">second</div>
</div>

huangapple
  • 本文由 发表于 2023年6月12日 01:41:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定