为什么按钮中的attr无法发送正确的数据?

时间:2018-11-29 14:10:56

标签: javascript jquery thymeleaf

    <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);
});

当我单击按钮时,控制台中显示“未定义”。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

jQuery data()仅适用于以data-开头的属性

将其更改为

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

另外,由于箭头函数没有显式的this,因此您不能在箭头函数中使用this

更改

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

收件人

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