首页 > 解决方案 > 当我单击其中任何一个对象时,循环中最后一个对象的脚本正在触发

问题描述

我一直在处理一个页面,该页面提取 JSON 数组的信息并循环通过它,显示一个可点击的徽标,其中包含更多信息的模态窗口。由于我看不到的原因,当我单击其中任何一个时,只有数组中的最后一个模态会触发。

我已经尝试将脚本移动到数组中,并将其单独的副本与我正在使用的代码内联,但我完全不知道它为什么会这样做。通过手动设置索引值,我能够让它触发数组中第一项的弹出窗口,但这不会是可持续的,因为每次添加新对象时我都必须不断添加它的新版本到JSON 数组。

jQuery(document).ready(function($) {
  var settings = {
    async: true,
    crossDomain: true,
    url:
      "https://api-url.com",
    method: "GET",
    headers: {
      accept: "api-json",
      authorization: "api-key"
    },
    data: "{}",
    contentType: "application/json",
    dataType: "json"
  };

  $.ajax(settings).done(function(response) {
    console.log(response);
    for (index in response.content) {
        $("#sponsors").append(
          '<a href="#" id="modalBtn' + [index] + '"><img src="' + response.content[index].logo + '"></a> \n' +
          
          // The Modal
          '<div id="' + [index] + '" class="sponsor-modal"> \n' +
          
            '<div class="sponsor-modal-content"><span class="close">&times;</span><p>' + response.content[index].name + '</p></div> \n' +
          
          '</div>'
            );
            // Get the modal
            var modal = document.getElementById([index]);

            // Get the button that opens the modal
            var btn = document.getElementById("modalBtn" + [index]);

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

            // 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";
              }
            }
        }
    })
});
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Speakers</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <style>
      /* The Modal (background) */
      .sponsor-modal {
        display: none; /* Hidden by default */
        position: fixed; /* Stay in place */
        z-index: 1; /* Sit on top */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgb(0, 0, 0); /* Fallback color */
        background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
      }

      /* Modal Content/Box */
      .sponsor-modal-content {
        background-color: #fefefe;
        margin: 15% auto; /* 15% from the top and centered */
        padding: 20px;
        border: 1px solid #888;
        width: 80%; /* Could be more or less, depending on screen size */
      }

      /* The Close Button */
      .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }

      .close:hover,
      .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
      }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>
    <div id="sponsors"></div>
  </body>
</html>


编辑:这是我正在处理的 JSON..

{
  "links": [
    {
      "rel": "self",
      "href": "https://api.url.com"
    }
  ],
  "content": [
    {
        "description": "Some Content Here",
        "level": 6,
        "logo": "https://url/llep2hufwsahu8eegbg0.png",
        "website": "http://url.com",
        "visible": true,
        "created": "2020-02-05T03:14:04.000+0000",
        "eventId": 215392,
        "name": "Name",
        "id": 217848,
        "type": "SPONSOR"
    },
    {
        "description": "Some Other Content Here",
        "level": 6,
        "logo": "https://url/jfdaklfjdkalda.png",
        "website": "http://url2.com",
        "visible": true,
        "created": "2020-01-21T17:22:05.000+0000",
        "eventId": 215392,
        "name": "Other Name",
        "id": 216197,
        "type": "SPONSOR"
    },
    {
        "description": "Some Additional Content Here",
        "level": 4,
        "logo": "https://url/fdsafdasfdafd.png",
        "website": "https://www.url2.com/",
        "visible": true,
        "created": "2020-01-21T17:19:24.000+0000",
        "eventId": 215392,
        "name": "Other Other Name",
        "id": 216195,
        "type": "SPONSOR"
    }
  ]
}

标签: javascriptjqueryjson

解决方案


改变

var modal = document.getElementById([index]);
var btn = document.getElementById("modalBtn" + [index]);
var span = document.getElementsByClassName("close")[index];

let modal = document.getElementById([index]);
let btn = document.getElementById("modalBtn" + [index]);
let span = document.getElementsByClassName("close")[index];

我认为。


推荐阅读