【问题标题】:How to use th:each to pass a string to JavaScript code embedded in html page如何使用 th:each 将字符串传递给嵌入在 html 页面中的 JavaScript 代码
【发布时间】:2022-02-02 23:15:36
【问题描述】:

我首先创建一个带有图像链接的测试列表。 然后我将它传递给名为_links的模型

    @GetMapping("/{id}")
    public String showItem(@PathVariable int id, Model model)
    {
        List<String> imageLinks = new ArrayList<>();
        imageLinks.add("/resources/static/images/products/1/product_test_image.jpg");
        imageLinks.add("/resources/static/images/products/1/product_test_image2.jpg");
        imageLinks.add("/resources/static/images/products/1/product_test_image3.jpg");
        
        model.addAttribute("_links", imageLinks);
        return "item/item";
    }

然后,在 html 代码中的某个位置,我绘制的按钮数量等于 _links 列表中的图片数量。
我可以将循环编号传递给 imgSrc 方法。但我不能传递 link 字符串本身。当我尝试发送它时,页面停止正常显示。因此,这一行被注释掉了。

    <div th:each="link, iStat : ${_links}">
        <span id="current_img" th:text="${link}"></span>
        <input type="image" th:src="${link}" alt="miniature" th:onclick="'imgSrc(\'' + ${iStat.index} + '\');'" style="width: 80px; height: 80px; margin: 3px">
   <!-- <input type="image" th:src="${link}" alt="miniature" th:onclick="'imgSrc(\'' + ${link} + '\');'" style="width: 80px; height: 80px; margin: 3px"> -->
    </div>

最后是我调用的方法。最后一行被注释掉了,但它显示了我想要实现的目标。 即通过点击列表中的图片,我想将大图片更改为循环中选择的新图片。

<script language="JavaScript">

            var selectedImage = document.getElementById("current_img");

            var mainImage = document.getElementById("main_product_image");
            var debug = document.getElementById("debug");
            var debug2 = document.getElementById("debug2");
            
            function imgSrc(link)
            {
                mainImage.src = selectedImage.innerHTML;
                debug.innerHTML = selectedImage.innerHTML;
                debug2.innerHTML = link;
//                mainImage.src = link;
            }

        </script>

奇怪的是 link 通常会传递给 th:text
提前感谢所有回答的人。

【问题讨论】:

    标签: javascript java html thymeleaf


    【解决方案1】:

    问题解决了。这是一个测试代码,它在消息中显示一个指向我们单击的按钮图像的链接。

    <!DOCTYPE html>
    
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    
    <head>
      <meta charset="UTF-8">
      <title>Item name</title>
      <link rel="stylesheet" type="text/css" href="/resources/static/css/styles.css">
    </head>
    
    <body style="margin: 0">
      <div class="page" style="margin: 0">
        <div th:each="link, iStat : ${_links}">
          <input type="image" th:src="${link}" value="Click me" onclick="buttonClick(this)">
        </div>
      </div>
    
      <script type="text/javascript">
        function buttonClick(e) {
          var att = e.getAttribute('src');
          alert(att);
        }
      </script>
    </body>
    
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多