Javascript Thymeleaf:如何搜索具有可变索引的数组?
如何使用一个变量作为数组的索引,通过HTML中带有JavaScript函数的Thymeleaf进行访问 在本例中,我想使用gcounter作为数组tlist的变量索引 输入工作正常 这个Javascript Thymeleaf:如何搜索具有可变索引的数组?,javascript,arrays,spring-boot,spring-mvc,thymeleaf,Javascript,Arrays,Spring Boot,Spring Mvc,Thymeleaf,如何使用一个变量作为数组的索引,通过HTML中带有JavaScript函数的Thymeleaf进行访问 在本例中,我想使用gcounter作为数组tlist的变量索引 输入工作正常 这个[${tlist[1].id}]也可以正常工作 但我需要一个可变索引 有什么想法吗 编辑: 我的问题与此非常相似: 函数saveFavorit(){ var counter=document.getElementById(“favoriteInput”).value var gcounter=编号(计数器);
[${tlist[1].id}]
也可以正常工作
但我需要一个可变索引
有什么想法吗
编辑:
我的问题与此非常相似:
函数saveFavorit(){
var counter=document.getElementById(“favoriteInput”).value
var gcounter=编号(计数器);
var idz=[${tlist[(var gcounter;)].id}];
“路径=/”;
document.cookie=“id=“+idz+”expires=“+”1999年12月31日星期五23:59:59 GMT”+“路径=/”;
}
您可以通过将单个步骤分解为两个步骤来完成此操作:
1) 从Thymeleaf填充JS变量(数据数组)
2) 使用输入字段中提供的值访问所需的数组条目
假设您有一个由User
对象组成的Java数组,类似于以下内容,带有用户ID和用户名
User user1 = new User(123, "Bob");
User user2 = new User(124, "Anne");
User user3 = new User(125, "Jane");
User[] users = { user1, user2, user3 };
…模板中有一个类似以下内容的输入字段:
<div>
<input id="favoriteInput"
maxlength="3"
name="favNummer"
required type="number"
onClick="saveFavorit();"/>
</div>
…然后您可以包含一个类似于以下内容的脚本:
<script th:inline="javascript">
function saveFavorit() {
var index = document.getElementById("favoriteInput").value;
var usersArray = [[${users}]];
if (index >= 0 && index <= usersArray.length - 1) {
var selectedUserName = usersArray[index].userName;
}
console.log(selectedUserName);
}
</script>
函数saveFavorit(){
var index=document.getElementById(“favoriteInput”).value;
var usersArray=[[${users}]];
如果(index>=0&&index,非常感谢!这正是我要找的
<script th:inline="javascript">
function saveFavorit() {
var index = document.getElementById("favoriteInput").value;
var usersArray = [[${users}]];
if (index >= 0 && index <= usersArray.length - 1) {
var selectedUserName = usersArray[index].userName;
}
console.log(selectedUserName);
}
</script>