首页 > 解决方案 > 为什么按钮中的 th:attr 没有发送正确的数据?

问题描述

    <th:block th:each="fh : ${datacenterFisicHosts}">
        <div>
            <tr class="row">
                <td id="fisicHostName" th:text="${fh.name}"></td>
                <td id="fisicHostIp" th:text="${fh.ip}"></td>
                <td id="fisicHostOS" th:text="${fh.operatingSystem}"></td>
                <td id="fisicHostNotes" th:text="${fh.notes}"></td>
                <td>
                    <button class="credentialsButton btn btn-default btn-sm" th:attr="data-fisic-host-id=${fh.id}">CREDENCIALES</button>
                </td>
                <td>
                    <button class="btn btn-default btn-sm btn-deleteFH" th:attr="data-fhId=${fh.id}">
                        <span class="glyphicon glyphicon-remove-sign"></span> Eliminar
                    </button>
                </td>
            </tr>
        </div>
    </th:block>
</table>

这很奇怪,因为这是有效的:

<button class="credentialsButton btn btn-default btn-sm" th:attr="data-fisic-host-id=${fh.id}">CREDENCIALES</button>

这不是:

<button class="btn btn-default btn-sm btn-deleteFH" th:attr="data-fhId=${fh.id}">
                        <span class="glyphicon glyphicon-remove-sign"></span> Eliminar
                    </button>

这是不工作问题的 JS 代码:

 $('.btn-deleteFH').click(function() {
    var fisicHostId = $(this).data('fhId');
    console.log(fisicHostId);
});

当我单击按钮时,我在控制台中得到一个“未定义”。

我究竟做错了什么 ?

标签: javascriptjquerythymeleaf

解决方案


jQuerydata()仅适用于以data-

将其更改为

th:attr="data-fhId=${fh.id}"

你也不能this在箭头函数中使用,因为箭头函数没有明确的this

改变

$('.btn-deleteFH').click( () => {

$('.btn-deleteFH').click(function() {

推荐阅读