风小筝123 2023-03-22 22:32 采纳率: 47.4%
浏览 24
已结题

thymeleaf 外部js中如何访问变量

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

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

1条回答 默认 最新

  • pzzhao 2023-03-22 23:02
    关注

    该回答引用自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文件的最后。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月31日
  • 已采纳回答 3月23日
  • 创建了问题 3月22日