0

我正在使用 Spring MVC,并且我有一个在数据库中搜索记录并将记录列表返回到另一个页面的表单。然而,返回的数据在标签上绘制图像。只有第一个图像被绘制在表单上,​​其余的不是。我知道这与 jquery 中的循环闭包有关,但我如何才能在这里克服它。

对 jscript 进行了一些编辑,但是只有第一张图像显示在所有画布上

JavaScript:

$(文档).ready(函数() {

    $(".photos").each(function(i){                      
        if ($(this).val() != '') {
            alert($(this).val());
            var image = new Image();
                var foto = $(".photos").val();                         
                image.src =  $(".photos").val();
                image.onload = function(){ 
                    //var foto = $(".photos").val();                         
                    //image.src =  $(".photos").val();
                     $(".canvas").each(function(i){
                         var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
                         ctx.drawImage(image,0,0, 320, 240); 
                     });                        
                }                   
        }
    });                     
});

CitizenList.jsp

<title>Citizen Search Results</title>
 </head>
  <body>
   <c:forEach items="${citizens}" var="citizen">
    <div><p><canvas class="canvas" height="240" width="320"></canvas></div>
        First name:- ${citizen.fName} , Last Name:- ${citizen.lName}
        <input type="text" value="${citizen.photo}" class="photos"/>
    </c:forEach>

   </body>
  </html>
4

2 回答 2

1

photo使用一个 id 多次创建输入框。

<input type="text" id="photo" value="${citizen.photo}"/>

在一个foreach.

<c:forEach items="${citizens}" var="citizen">

它将像这样呈现html:

<div><p><canvas id="canvas" height="240" width="320"></canvas></div>
    First name:-Jim , Last Name:- Doe
    <input type="text" id="photo" value="xyz"/>

<div><p><canvas id="canvas" height="240" width="320"></canvas></div>
    First name:- Bob , Last Name:- Doe
    <input type="text" id="photo" value="abc"/>

当然,您的 jQuery 查找$("#photo")只匹配第一个。


相反,您可以给它们一个类并迭代它们:

<input type="text" id="photo${status.id}" class="photo" value="${citizen.photo}"/>

并使用 jQuery foreach 遍历它们

$('.photo').each(function(){ //..
于 2013-03-08T17:39:35.730 回答
1

图片来源需要参考$(this).val()。无需遍历每个画布,只需要使用索引移动到当前画布即可。下面是完整的解决方案:

 <script type="text/javascript">

    $(document).ready(function() {

            $(".photos").each(function(i){                      
                if ($(this).val() != '') {
                       var image = new Image();                      
                        image.src =  $(this).val();

                        image.onload = function(){ 
                                 var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
                                 ctx.drawImage(image,0,0, 320, 240); 
                         }               
                }
            });                     
        });

    </script>
于 2013-03-09T01:24:35.993 回答