使用javascript通过数组Thymeleaf循环

问题描述 投票:0回答:3

我有一个名为“products”的数组变量(来自后端)。它具有以下结构: - 产品 - - -特别 ---------- 0 - - - - - - - -ID - - - - - - - -价钱 - - - - - - - -等等..... ---------- 1 - - - - - - - -ID - - - - - - - -价钱 - - - - - - - -等等 ---------- 2..etc

我正在使用百里香。我试图在javascript中循环“特殊产品”并尝试使用它们的索引来获取子数据(id,price等)。我试图使用一个名为“counter”的新整数变量来访问索引。所以我的代码是:

<script th:inline="javascript" th:with="setProducts=(${products.special})">
    function LetsSayLoop() {
        var counter = 0;
        //looping through some checkboxes
        $('#checkboxContainer .checkboxesClassName').each(function() {
            if($(this).is(":checked")) {
                //this is working:
                var current_product_price = [[${setProducts[0].price}]];
                //this is also working:
                //var current_product_price = [[${setProducts[1].price}]];
                //etc...

                //this is not working:
                var current_product_price = [[${setProducts[counter].price}]];
                counter++;
            }
        }); 
    }
</script>

我的IDE(netbeans)说没有使用变量“counter”。生成的Javascritp和HTML也以下结尾:任何想法为什么?

var current_product_price = 

编辑:关于javascript循环的小补充:

//[[${#lists.size(setProducts)}]] outputs the desired integer;
for (i = 0; i < [[${#lists.size(setProducts)}]]; i++) {
    //this is working:
    console.log([[${setProducts[0].price}]]);
    //this is not:
    console.log([[${setProducts[i].price}]]);
}

编辑:(可能的答案?) 我知道百里香叶不能识别[[]]范围内的局部javascript变量。例如:

var current_product_price = [[${setProducts[counter].price}]];

代码期望变量“counter”来自百日咳。我需要使用索引来做,但使用局部变量它不起作用。我可以增加一些本地js变量来完成这个吗?或者是其他方式?

javascript thymeleaf
3个回答
1
投票

如果你改变jquery.eachforEach它应该工作。这是一个例子

 function a() {
      var counter =0;
      [1, 2, 3, 4].forEach(function(e){
              console.log('Element:', e);
              console.log('Counter:', counter++);
      });
 }

 a();

1
投票

代码看起来很好,所以它应该工作。

如果唯一的问题是您在IDE上看到的警告,我不担心,这可能是一个错误。

但是,您不需要使用计数器,您可以使用.each使用的内置变量:

.each(function( index, element ) {
  //Use index instead of counter.
}

编辑:

好的,我想我现在明白了这个问题:

你不能在这种表达式中使用javascript变量。将其分解为两个 - 首先从数组创建一个js变量,然后像这样使用[index]:

function LetsSayLoop() {
    var current_Products = [[${setProducts}]]; //btw not sure about double brackets
    //looping through some checkboxes
    $('#checkboxContainer .checkboxesClassName').each(function(index) {
        if($(this).is(":checked")) {

            //this should work:
            var current_product_price = current_Products[index];
            //etc...  
        }
    }); 
}

0
投票

我还不能评论,所以我会发一个答案。

请将此行添加到each调用中,并向我们显示计数器是否实际可用于each范围并更新。接下来你会知道实际调用了多少次。

alert("Counter val: " + counter.toString());
© www.soinside.com 2019 - 2024. All rights reserved.