【问题标题】:JQuery click event not workiong on ThymeleafJQuery点击事件不适用于Thymeleaf
【发布时间】:2019-07-29 01:43:23
【问题描述】:

我正在使用 Spring Boot 开发一个网站。我有一个元素列表,每个元素都有一个链接。我想在按下链接时调用 javascript 函数。 我有这个代码

<div class="col-sm-4" th:each="product : ${productsList}">
  <!-- Code... -->
  <a th:id="${'buyButton' + product.id}" <!-- rest of attributes -->></a>
  <!-- More code... -->
  <script th:inline="javascript">
    /*<![CDATA[*/
      console.log("Log1");
      $("#buyButton[[${product.id}]]").click(function() {
        console.log("Log2");
      });
    /*]]>*/
  </script>
</div>

productsList 有 5 个元素,所以当我加载页面时,它会打印五次“Log1”,但是当我点击链接时,打印“Log2”的功能不起作用。

谁能帮帮我。我要疯了……

【问题讨论】:

  • 你能看看浏览器中的 JavaScript 代码是如何被 thymeleaf 渲染的吗?
  • 是的。我检查它,我可以看到脚本块。选择器没问题 #buyButton1、#buyButton2 等...这不是 thymeleaf 解析错误。太奇怪了。
  • 我也在网络标签上记录了动作,但是点击事件没有触发

标签: javascript jquery spring-boot thymeleaf


【解决方案1】:

使用类选择器$('.ClassName')为锚元素和附加事件处理程序分配一个公共类,即productBuyButton

<div class="col-sm-4" th:each="product : ${productsList}">
  <!-- Code... -->
  <a class="productBuyButton" th:id="${'buyButton' + product.id}" <!-- rest of attributes -->></a>
  <!-- More code... -->

</div>

<script th:inline="javascript">
      $(".productBuyButton").click(function() {
        console.log(this.id);
        //Here `this` refers to element which invoked the event handler
      });
</script>

如果您想保留现有代码,请将选择器更改为 $('#buyButton${product.id}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2017-06-10
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多