我正在使用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”的功能不起作用。
谁能帮我。我要疯了...
使用类选择器productBuyButton
为锚元素和附加事件处理程序分配一个公共类,即$('.ClassName')
<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}')