Django htmx 未定位指定元素

问题描述 投票:0回答:1

我有一个 django-tables2 模板,我已对其进行了修改,为每一行分配唯一的行 id。我正在尝试添加一个按钮,允许用户单击即可删除给定行。我正在使用 htmx 发起删除请求。我还有一个启用 htmx 的编辑按钮,它在服务器端修改和更新 DOM 方面按预期工作。删除按钮的行为与服务器端的预期一致,但交换似乎仅影响按钮,而不影响标签。单击删除按钮后,记录会从数据库中删除,但 DOM 上只有按钮消失,而不是

<tr>
。我不会包含views.py,因为它相当简单,因为它检索适当的记录,执行删除,并返回一个空的HTTPResponse。

我尝试添加带有 hx-swap 的 hx-target,但这会停用按钮上的任何 htmx 调用功能。我还尝试在

<div>
周围放置一个
<tr>
包装器,并通过我的 oob 交换来瞄准它,但没有运气。

这是带有编辑和删除按钮的 table.tbody 模板:

{% extends 'tablestyle.html' %}
{% load humanize %}
{% block table.tbody %}

<tbody {{ table.attrs.tbody.as_html }}>
    {% for row in table.paginated_rows %}
        {% block table.tbody.row %}
        <tr id="emp_hx_row_{{ row.record.pk }}" {{ row.attrs.as_html }} height="70px">
            {% for column, cell in row.items %}
            <td {{ column.attrs.td.as_html }} class="gls-text-middle">    
                {{ cell }}                           
            </td>
            {% endfor %}
            <td class="gls-flex gls-align-middle">                
                <!-- edit button -->
                <div class="gls-width-auto">
                    <button class="gls-flex gls-flex-center gls-flex-middle" hx-get="{% url 'employment_history_edit' row.record.pk %}" gls-tooltip="title: Edit" title="" aria-expanded="false" tabindex="0">
                        <div class="fa fa-edit fa-xs" style="color:#000000"></div>
                    </button>
                </div>
        
                <!-- delete button -->
                <div class="gls-width-auto gls-margin-small-left">
                    <button class="gls-flex gls-flex-center gls-flex-middle" gls-tooltip="title: Delete" hx-delete="{% url 'employment_history_delete' row.record.pk %}" hx-confirm="Are you sure you wish to delete?" hx-swap-oob="#emp_hx_row_{{ row.record.pk }}">
                        <div class="fa fa-trash fa-xs" style="color:#000000"></div>
                    </button>
                </div>
            </td>
        </tr>
        {% endblock table.tbody.row %}
    {% empty %}
        {% if table.empty_text %}
        {% block table.tbody.empty_text %}
        <tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
        {% endblock table.tbody.empty_text %}
        {% endif %}
    {% endfor %}
</tbody>

{% endblock %}
html django django-tables2 htmx
1个回答
0
投票

您应该能够使用相对定位删除该行:

<button
    class="gls-flex gls-flex-center gls-flex-middle"
    gls-tooltip="title: Delete"
    hx-delete="{% url 'employment_history_delete' row.record.pk %}"
    hx-confirm="Are you sure you wish to delete?"
    hx-target="closest tr"
    hx-swap="outerHTML swap:1s"
>
    <div class="fa fa-trash fa-xs" style="color:#000000"></div>
</button>

您应该返回包含空内容的 200 响应,以指示 htmx 删除目标内容而不是用任何内容替换它。

为了避免重复的属性,您可以用表单包裹表格,并将所有

hx-
属性移至表单标签(
hx-delete
除外)。

您还可以查看 htmx 文档中的示例代码以获取更多详细信息:

https://htmx.org/examples/delete-row/

© www.soinside.com 2019 - 2024. All rights reserved.