You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在htmx更新目标区域时保留指定div的内容?

解决方案

有几种简便的方式可以实现保留指定div不被更新,避免筛选、滚动状态丢失:

方法1:拆分容器(最直观可靠)

调整HTML结构,把需要更新的内容单独放到一个子容器中,让htmx只更新这个子容器,保留的div作为同级元素独立出来。这种方式完全不会触动保留div的状态:

<div id="large-section">
  <!-- 仅更新这个子容器 -->
  <div id="updatable-content"
       hx-get="/large-section-details/"
       hx-trigger="sectionUpdated from:body">
    <div>Some section content which gets updated</div>
    <div>Some more section content which gets updated</div>
    <div>Some more section content which gets updated</div>
    <div>Some more section content which gets updated</div>
  </div>
  <!-- 这个div始终保留,状态不受更新影响 -->
  <div>
    I would like this div only to remain unchanged when `sectionUpdated` is raised. 
  </div>
</div>

方法2:使用hx-preserve属性

给需要保留的div添加唯一ID和hx-preserve属性,htmx在更新父容器时会自动保留该元素(需确保服务器返回的HTML中包含相同ID的div,内容可空):

<div
  id="large-section"
  hx-get="/large-section-details/"
  hx-trigger="sectionUpdated from:body"
>
  <div>Some section content which gets updated</div>
  <div>Some more section content which gets updated</div>
  <div id="keep-this-div" hx-preserve>
    I would like this div only to remain unchanged when `sectionUpdated` is raised. 
  </div>
  <div>Some more section content which gets updated</div>
  <div>Some more section content which gets updated</div>
</div>

服务器返回的/large-section-details/内容中,只需包含<div id="keep-this-div" hx-preserve></div>即可,htmx会自动保留页面中原有的该元素及其状态。

方法3:用hx-select筛选更新内容

通过hx-select指定只更新目标容器中除保留div之外的元素,适用于无法调整页面结构的场景:

<div
  id="large-section"
  hx-get="/large-section-details/"
  hx-trigger="sectionUpdated from:body"
  hx-select="div:not(#keep-this-div)"
>
  <div>Some section content which gets updated</div>
  <div>Some more section content which gets updated</div>
  <div id="keep-this-div">
    I would like this div only to remain unchanged when `sectionUpdated` is raised. 
  </div>
  <div>Some more section content which gets updated</div>
  <div>Some more section content which gets updated</div>
</div>

htmx会从服务器返回的HTML中筛选出除#keep-this-div外的所有div,替换到large-section中,原保留div的状态得以完整保留。


内容的提问来源于stack exchange,提问作者François Constant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:24:32