Доступ к объектам в массиве JSON для генерации содержимого модального окна - PullRequest
0 голосов
/ 19 февраля 2020

У меня есть 6 bootstrap карт, сгенерированных из 6 объектов, каждая карта имеет кнопку, которая получает идентификатор данных из идентификаторов объектов. Когда я нажимаю кнопку, я бы хотел, чтобы содержимое, соответствующее этому идентификатору, появилось в его собственном модальном окне, но все появляется прямо сейчас. Как мне этого добиться?

Изображение карты:

enter image description here

Изображение всех отображаемых данных:

enter image description here

main. js

var data = [
  {id: 0, name: 'Cause1', desc: 'This is cause 1', descLong: "This is a longer description of cause 1", votes: 10, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 1, name: 'Cause2', desc: 'This is cause 2', descLong: "This is a longer description of cause 2", votes: 20, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 2, name: 'Cause3', desc: 'This is cause 3', descLong: "This is a longer description of cause 3", votes: 30, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 3, name: 'Cause4', desc: 'This is cause 4', descLong: "This is a longer description of cause 4", votes: 40, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 4, name: 'Cause5', desc: 'This is cause 5', descLong: "This is a longer description of cause 5", votes: 50, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 5, name: 'Cause6', desc: 'This is cause 6', descLong: "This is a longer description of cause 6", votes: 60, votesTarg: 100, image: "https://via.placeholder.com/220"}
];

  for (var i=0; i < data.length; i++){
document.getElementById('row').innerHTML += ("<div class='col-md-4'><div class='card mb-4 mt-4 shadow border-0'><img class='rounded-top' src='" + data[i]["image"] +"'/><div class='card-body'><h5 class='font-weight-bolder'>" + data[i]["name"] + "</span></h5><p> " + data[i]["desc"] + "</p><button type='button' class='btn btn-primary readmore' data-toggle='modal' data-target='#modal-info' data-id='" + data[i]["id"] + "' value='" + data[i]["id"] + "'>Read more</button></div><div class='card-footer auto'><p class='vote-counter text-center m-0 p-0'>" + data[i]["votes"] + " / " + data[i]["votesTarg"] + " signatures" + "</p></div><div class='progress rounded-bottom'><div class='progress-bar primary' role='progressbar' ariavalue='30' aria-valuemin='0' aria-valuemax='100'><span class='sr-only'>10% Complete</span></div></div></div></div>");


document.getElementById('modal-title').innerHTML += data[i]["name"];
document.getElementById('modal-desc').innerHTML += data[i]["descLong"];
}

index. html

<div class="modal fade modal1" id="modal-info" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modal-title"></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md" id="modal-desc"></div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Sign the Cause</button>
          </div>
        </div>
      </div>
    </div>

1 Ответ

0 голосов
/ 20 февраля 2020

Вы добавляете все объекты данных без проверки идентификатора карты.

Пожалуйста, попробуйте это:

    /*
    please replace readmoreElement (I just used that name to convey the point - to retrieve data-id attribute value) with your button element (or) use event.target.id. 
    I am assuming you are invoking this on the button click of "Read More". so, in the button click event, you will get id of the button via event.target.id 
    */
        var temp = readmoreElement.getAttribute('data-id'); // document.getElementById(event.target.id).getAttribute('data-id');
        // instead of for loop you can pluck the element by using underscore or lodash library functions.
        for (var i=0; i < data.length; i++){
            if (temp === i)
            {
                document.getElementById('row').innerHTML += ("<div class='col-md-4'><div class='card mb-4 mt-4 shadow border-0'><img class='rounded-top' src='" + data[i]["image"] +"'/><div class='card-body'><h5 class='font-weight-bolder'>" + data[i]["name"] + "</span></h5><p> " + data[i]["desc"] + "</p><button type='button' class='btn btn-primary readmore' data-toggle='modal' data-target='#modal-info' data-id='" + data[i]["id"] + "' value='" + data[i]["id"] + "'>Read more</button></div><div class='card-footer auto'><p class='vote-counter text-center m-0 p-0'>" + data[i]["votes"] + " / " + data[i]["votesTarg"] + " signatures" + "</p></div><div class='progress rounded-bottom'><div class='progress-bar primary' role='progressbar' ariavalue='30' aria-valuemin='0' aria-valuemax='100'><span class='sr-only'>10% Complete</span></div></div></div></div>");


                document.getElementById('modal-title').innerHTML += data[i]["name"];
                document.getElementById('modal-desc').innerHTML += data[i]["descLong"];

                break;
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...