代码之家  ›  专栏  ›  技术社区  ›  crystopher cr

无法使用js获取输入值

  •  1
  • crystopher cr  · 技术社区  · 2 年前

    我有一个使用thymeleaf的循环输入,我需要在每次迭代悬停时获得值并计算和

     <tr th:each="person : ${persons}">
                <td th:text="${person.first_name}"></td>
                <td th:text="${person.last_name}"></td>
                <td th:text="${person.phone}"></td>
                <td><input id="age" class="form-control"
                            type="text" name="age" th:field="*{ages}">
                </td>
        </tr>
    
    Total : <input type="text" name="sum" id="sum"/>
    

    我的js脚本:

    <script type="text/javascript">
        $(document).ready(function(){
              $("#age").each(function() {
    
                $(this).on('input', function(){
                  calculateSum();
                });
                
                console.log("sum :"+sum);
              });
    
            });
    
            function calculateSum() {
    
              var sum = 0;
              $("#age").each(function() {
                if(!isNaN(this.value) && this.value.length!=0) {
                  sum += parseFloat(this.value);
                }
    
              });
              $("#sum").html(sum.toFixed(2));
    
            }
        </script>
    

    我的代码只给出了第一个值(就像它在第二次迭代中不起作用一样),我不知道为什么!!

    1 回复  |  直到 2 年前
        1
  •  0
  •   Unmitigated    2 年前

    ID在页面上应该是唯一的;因此,id选择器通常只返回具有该id的第一个元素。您应该改用类。

    <input class="age" class="form-control" type="text" name="age">
    

    然后,您的选择器应成为:

    $(".age").each(function(){
        // ...
    });