如何使用th:each将一个字符串传递给嵌入html页面的JavaScript代码



我首先创建一个带有图像链接的测试列表。然后我将其传递给名为_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方法。但是我无法传递链接字符串本身。当我尝试发送它时,页面将停止正常显示。因此,这一行被注释掉了。

<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>

奇怪的是,链接通常被传递到th:text
提前感谢所有回答的人。

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

<!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>

最新更新