thymeleaf 外部js中如何访问变量

thymeleaf 外部js中如何访问变量?
thymeleaf 外部js中如何访问变量?
thymeleaf 外部js中如何访问变量?
thymeleaf 外部js中如何访问变量?

<script th:src="@{/static/pages/customer/customer_list.js}">script>

该回答引用自ChatGPT

在Thymeleaf中,要在外部JS中访问Thymeleaf变量,需要将变量的值传递给JS文件。可以使用data-*属性将变量的值存储在HTML元素中,然后在JS文件中使用getAttribute()方法获取这些值。以下是一个示例代码:
在HTML文件中,将变量的值存储在一个data-*属性中:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Thymeleaf Example</title>
  <script th:inline="javascript">
    // 将变量的值存储在一个data-*属性中
    var customerId = [[${customerId}]];
    document.getElementById("customerId").setAttribute("data-customer-id", customerId);
  </script>
</head>
<body>
  <div id="customerId"></div>
  <script th:src="@{/static/pages/customer/customer_list.js}"></script>
</body>
</html>

在JS文件中,使用getAttribute()方法获取变量的值:


// 获取data-customer-id属性的值
var customerId = document.getElementById("customerId").getAttribute("data-customer-id");
console.log(customerId);

在这个示例代码中,我们首先将customerId变量的值存储在一个data-customer-id属性中,然后在JS文件中使用getAttribute()方法获取这个值,并将其输出到控制台中。请注意,为了确保JS文件在HTML文件中加载后才能执行,我们将JS文件的引入放在了HTML文件的最后。