简体   繁体   English

显示/隐藏的Javascript <c:forEach> JSTL的div元素

[英]Javascript to show/hide <c:forEach> div element of JSTL

I have an JSTL for each tag as follows. 每个标签都有一个JSTL,如下所示。

  <c:forEach items="${schedule}" var="period">
               <td>
                   <div id="friends">    
                     ${period.getFriends()}
                </div>
                 </td>
     </c:forEach>

I want to implement a button that on click will hide or show all these blocks. 我想实现一个按钮,单击该按钮将隐藏或显示所有这些块。 So far all the button does is hide or show the first element of the block. 到目前为止,所有按钮所做的只是隐藏或显示块的第一个元素。 I dont know why it doesn't iterate through all the block. 我不知道为什么它不会遍历所有块。

<button onclick="myFunction()" class="btn btn-success btn-xs">With friend</button>
                        <button class="btn btn-danger btn-xs">Without friend</button>
                        <script>
                            function myFunction() {
                                var div = document.getElementById('friends');
                                div.innerHTML = "AFJASFAS";
                            }
                        </script>

As you can see I didn't really implement the show and hide for the buttons yet. 如您所见,我还没有真正实现按钮的显示和隐藏。 I just tests it by adding in extra text however, this text is only added to the first div. 我只是通过添加额外的文本来对其进行测试,但是,此文本仅添加到第一个div中。 How can i make it so it applies to all the elements? 我怎样才能使它适用于所有元素?

That's obvious, because you are using one ID for all blocks! 显而易见,因为所有块都使用一个ID! ID must be unique in the html page, but you have many <div id="friends"> . ID在html页面中必须唯一,但是您有许多<div id="friends"> When you have some elements with same ID, javascript select first element. 如果您有一些具有相同ID的元素,请使用javascript选择第一个元素。 Solution is to use Class instead of ID: 解决方案是使用Class而不是ID:

<c:forEach items="${schedule}" var="period">
           <td>
               <div class="friends">    
                 ${period.getFriends()}
            </div>
             </td>
 </c:forEach>

 function myFunction() {
      var div = document.getElementsByClassName("friends");
      div.innerHTML = "AFJASFAS";
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM