从c:foreach调用javascript

时间:2016-12-29 06:47:52

标签: jsp jstl jsp-tags

我需要在c:foreach中调用javascript函数。请给我一个如何打电话的想法。我将在foreach中循环使用usertimetrackersummary,并且需要为每个循环调用javascript函数。

现在每次循环都会调用javascript函数,但如果我尝试打印“totalOffHomeHrs”,那么我将获得空值。在表数据中。 TD

  <c:forEach items="${userTimeTrackerSummary}" var="userTimeTracker">
            <script type="text/javascript">
                var totalOffHomeHrs= addTimes('${userTimeTracker.totalWorkhours}','${userTimeTracker.totalWorkHomehours}');
            </script>
          <tr style="font-size:11px;">
                    <td ><c:out value="${userTimeTracker.employeeID}" /></td>
                    <td>${totalOffHomeHrs}</td>
          </tr>
        </c:forEach>

    javascript function:
    function addTimes(t0, t1) {
          return timeFromMins(timeToMins(t0) + timeToMins(t1));
        }

1 个答案:

答案 0 :(得分:1)

最后我能够在下面的代码中达到要求。请建议是否有另一种优雅的方式。

<c:forEach items="${userTimeTrackerSummary}" var="userTimeTracker">
           <tr style="font-size:11px;">
                 <td ><c:out value="${userTimeTracker.employeeID}" /></td>
                 <td id="finalWorkHours${userTimeTracker.employeeID}"></td>
                        <script type="text/javascript">
                            var totalOffHomeHrs= addTimes('${userTimeTracker.totalWorkhours}','${userTimeTracker.totalWorkHomehours}');
                            document.getElementById('finalWorkHours${userTimeTracker.employeeID}').innerHTML = totalOffHomeHrs;
                        </script>
              </tr>
            </c:forEach>

javascript function:
function addTimes(t0, t1) {
      times = [];
      times1 = t0.split(':');
      times2 = t1.split(':');

      for (var i = 0; i < 2; i++) {
        times1[i] = (isNaN(parseInt(times1[i]))) ? 0 : parseInt(times1[i])
        times2[i] = (isNaN(parseInt(times2[i]))) ? 0 : parseInt(times2[i])
        times[i] = times1[i] + times2[i];
      }

      var minutes = times[1];
      var hours = times[0];

      if (minutes % 60 === 0) {
        res = minutes / 60;
        hours += res;
        minutes = minutes - (60 * res);
      }

      return hours + ':' + minutes ;
}