Как отобразить массив изображений с помощью JS и использовать Lightbox2

Как отобразить все изображения из массива в JS и при этом использовать Lightbox2?

Учитель математики 8-го класса пытается создать доску изображений «Крестики-нолики», где Lightbox2 позволяет пользователям щелкать, чтобы увеличивать изображения. В коде вы увидите, что я рандомизировал массив, чтобы моим детям было сложнее обманывать. Однако основное внимание уделяется тому, чтобы массив отображал каждое изображение в сетке 3x3, но позволял учащимся щелкать и увеличивать каждое изображение с помощью модального окна.

Для Lightbox2 требуется следующая строка кода:
a href="images/image-1. jpg" data-lightbox="image-1" data-title="My caption">Image #1 /a Вот почему у меня есть все неэффективные знаки + в коде js document.write.

Я искал ответ здесь, где ответы редактируют DOM или увеличивают массив, используя .foreach, я еще не видел решения, в котором вы все еще можете щелкнуть, чтобы увеличить изображение в модальном окне. Спасибо вам и мои ученики скажут спасибо! Это моя первая попытка привнести информатику в класс, так что я совсем нуб.

<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<link href="https://fonts.googleapis.com/css?
family=Oswald:300,700|Varela+Round" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tictactoestyle.css">
<link href="css/lightbox.css" rel="stylesheet">
<script type="text/javascript" src="tictactoe.js"></script>
<script src="js/lightbox-plus-jquery.js"></script>
</head> 

<body>
<div class="title">
<h1>  Tic Tac Toe </h1>
</div>

<div id="gameboard">  <!--Container for all nine divs-->

<script>displayAllImages();</script>
</div>
</body>
</html>

/*Javascript*/

function shuffle(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = arr[currentIndex];
    arr[currentIndex] = arr[randomIndex];
    arr[randomIndex] = temporaryValue;
}

return arr;

function displayAllImages() {
var imgArray = [];
imgArray[0] = "image1";
imgArray[1] = "image2";
imgArray[2] = "image3";
imgArray[3] = "image4";
imgArray[4] = "image5";
imgArray[5] = "image6";
imgArray[6] = "image7";
imgArray[7] = "image8";
imgArray[8] = "image9";

imgArray = shuffle(imgArray);

for (i=0;i<imgArray.length;i++) {
    document.write("<div class='card'><a href='images/" + item + "'.jpg 
data-lightbox='" + item + "'><img src='images/" + item + "m.jpg'></a>
</div>");

person mister    schedule 12.07.2017    source источник


Ответы (1)


Несколько вещей, которые вам нужно сделать. Во-первых, вы не можете просто добавить div в виде строки и записать ее в DOM. jQuery позволяет вам сделать что-то подобное, но ванильный JS не распознает его как фактический элемент. Там также было несколько недостающих скобок. Я добавил встроенные комментарии, чтобы прояснить ситуацию. Попробуйте это:

function shuffle(arr) {
  var currentIndex = arr.length, temporaryValue, randomIndex;

      // While there remain elements to shuffle...
  while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = arr[currentIndex];
      arr[currentIndex] = arr[randomIndex];
      arr[randomIndex] = temporaryValue;
  }

  return arr;
}


function displayAllImages() {
  var imgArray = [
    "image1",
    "image2",
    "image3",
    "image4",
    "image5",
    "image6",
    "image7",
    "image8",
    "image9",
  ];

  //Map over the array to create the DOM elements
  var domElements = imgArray.map(function(imgName, index) {
    var cardDiv = document.createElement('div');
    var cardLink = document.createElement('a');
    var cardImage = document.createElement('img');

    //Add the class
    cardDiv.classList.add('card');

    //Add the link to image
    //Utilize interpolation for the variable
    //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
    cardLink.href = `images/${imgName}.jpg`;

    //Set the data attribute
    cardLink.dataset.lightbox = imgName;

    //Set img source
    cardImage.src = `images/${imgName}.jpg`;

    //Put it all together
    cardLink.appendChild(cardImage);
    cardDiv.appendChild(cardLink);

    return cardDiv;

  });

  //Now we have an array with the propper DOM elements
  //Shuffle it
  var shuffled = shuffle(domElements);

  //Append the elements to the DOM
  var body = document.querySelector('body');

  shuffled.forEach(function(card, index) {
    body.appendChild(card);
  });
}

Надеюсь, что это поможет указать вам в правильном направлении. Удачного кодирования!

person RickTakes    schedule 12.07.2017
comment
Спасибо, это сработало как чемпион. Я все еще просматриваю ваши ссылки и комментарии, чтобы понять, что вы сделали. Отправляйтесь в Codecademy, большое спасибо. @RickTakes - person mister; 12.07.2017