循环中的动态模态

时间:2017-12-03 14:29:31

标签: javascript

我正在尝试在循环中执行动态模式。除了模态内容与每个模态的循环中的最后一个模态相同的事实之外,它工作正常。这意味着如果我打开第一个模态,内部的内容将是假设仅在最后一个模式上的内容。如果我打开第二个,也是一样的。我不知道如何解决这个问题。

{% for dr in results %}

    <button id="myBtn{{dr.id}}">More Info</button>
    <div id="myModal{{dr.id}}" class="modal">

      <!-- Modal content -->
      <div class="modal-content">
        <span class="close">&times;</span>
        <p class="modal-info"> Name: {{dr.driver__first_name}} </p>
        <p class="modal-info"> Phone number: {{dr.driver__phone_number}}</p>
        <p class="modal-info">Bus Type: </p>
        <p class="modal-info">License Plate:</p>

      </div>

    </div>

</div>      


    <script>
// Get the modal
var modal = document.getElementById("myModal{{dr.id}}");

// Get the button that opens the modal
var btn = document.getElementById("myBtn{{dr.id}}");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>


{% endfor %}

0 个答案:

没有答案