首页 > 解决方案 > thymeleaf onclick 参数

问题描述

我尝试将对象传递给 th:onclick。当我传递一个字符串(afficherDetails() 函数)时,一切正常当我传递一个对象(afficherDetails2() 函数)时,在被调用的函数中,该对象似乎没问题,但它是空的。

function afficherDetails(employee) {
   console.log("afficher Details");

   document.getElementById("detailledFirstNameDataLabelId").textContent = employee.firstName;
   document.getElementById("detailledLastNameDataLabelId").textContent = employee.lastName;
   document.getElementById("detailledAddressDataLabelId").textContent =  employee.address;
   document.getElementById("detailledTitleDataLabelId").textContent =  employee.title;
   document.getElementById("detailledManagerDataLabelId").textContent =  employee.manager;
}
function afficherDetails2(name) {
   console.log("afficher Details");

   document.getElementById("detailledFirstNameDataLabelId").textContent = name;

}
                <td><button  th:data-parameter1="${employee}" th:onclick=" afficherDetails(this.getAttribute('data-parameter1')) ">details</button></label></td>
                <!--td><button  th:data-parameter1="${employee.firstName}" th:onclick=" afficherDetails2(this.getAttribute('data-parameter1')) ">details</button></label></td-->
            </tr>

这是正确的行为吗?我们不能传递一个复杂的对象而我们只能传递一个简单的对象吗?

感谢您的回答

标签: onclickthymeleaf

解决方案


简短的回答:

您可以将复杂对象传递给 HTML 属性 - 但它会被对象的toString()方法简化为字符串。

因此,在您的情况下,尝试在 JavaScript 中执行以下操作...

var something = employee.firstName;

...不会做任何事情,因为函数传递的是字符串而不是对象 - 因此employee.firstNameundefined在 JavaScript 中。


更长的答案:

请记住几点:

  1. HTML 属性需要包含一个字符串:
<button th:data-parameter1="SOME VALUE IN HERE" ... >

因此,data-parameter1Thymeleaf 将使用字符串填充该属性。

  1. 所有 Thymeleaf 处理都发生在服务器上。Thymeleaf 从模板中删除其所有处理指令,并用有效的 HTML 替换它们。您的 JavaScript 无法访问原始 Java 对象 - 只能访问Thymeleaf 添加到 HTML 中的该对象的任何表示。

假设您使用以下内容:

th:data-parameter1="${employee.firstName}"

假设employee.firstName计算为一个字符串 ( John),那么这就是 Thymeleaf 将用来产生这个的:

data-parameter1="John"

但如果你试试这个:

th:data-parameter1="${employee}"

假设employee是您的自定义 Java bean,那么 Thymeleaf 将调用其toString()方法以用作字符串。

如果您没有toString()在您的Employee类中定义方法,那么将使用底层Object.toString()方法 - 您将看到类似以下内容 - 唯一对象的字符串表示形式,基于对象的名称和哈希码:

data-parameter1="org.yourpackage.Employee@bcb8097"
    

toString()你可以在你的类中提供你自己的实现Employee来提供更多有用的信息。但它必须是一个可以放在 HTML 属性中的字符串。


例如,如果您将 an 传递ArrayList给按钮:

List<String> names = Arrays.asList("John", "Mary");

和:

th:data-parameter1="${names}"

那么您的 HTML 按钮将包含以下内容:

data-parameter1="[John, Mary]"

因为[John, Mary]是如何ArrayList实现其toString()方法的结果。


您可以将某些 Java 对象直接发送到 JavaScript - 请参阅JavaScript 序列化。但这可能与这个问题无关。


一个额外的说明:在以下:

th:onclick="afficherDetails(this.getAttribute('data-parameter1'));"

您正在使用th:onclick- 但属性中没有 Thymeleaf 表达式,因此 Thymeleaf 无需处理任何内容。您可以使用:

onclick="afficherDetails(this.getAttribute('data-parameter1'));"

推荐阅读