Получить первые 6 элементов из массива

Я думаю, что event.stopPropagation(); следует упомянуть здесь. Добавьте это к функции щелчка вашей кнопки.

Предотвращает появление пузырьков в дереве DOM, предотвращая уведомление любого из обработчиков родительских событий.

0
задан Ros5292 16 January 2019 в 02:09
поделиться

4 ответа

Ошибка 404 из-за этого:

// you're setting the src of the image as 'https://image.tmdb.org/t/p/w500/val1/val2/val3/val4/val5/val6' which doesn't make sense
tvImage.src = img + tvSeriesImg.slice(0, 6);

Попробуйте заменить этот блок:

console.log(tvSeriesImg.slice(0, 6));


        const tvImage = document.createElement('img');
        tvImage.src = img + tvSeriesImg.slice(0, 6);
        tvImage.setAttribute('id', 'movieThumb');
        popTvSeriesCard.appendChild(tvImage);

на это:

tvSeriesImg.slice(0, 6).map((imgUrl) => {
    const tvImage = document.createElement('img');

    // set src = "https://image.tmdb.org/t/p/w500/valx" where '/valx' is the imgUrl.
    tvImage.src = img + imgUrl;
    tvImage.setAttribute('id', 'movieThumb');
    popTvSeriesCard.appendChild(tvImage);
})

Надеюсь, это поможет! [ 116]

0
ответ дан Ray Mata 16 January 2019 в 02:09
поделиться

Вот упрощенный метод forEach, который решит вашу проблему.

const cards = document.getElementById('tv-series-data')

results.forEach(result => {

  const card = document.createElement('div')
  card.id = result.id // ID's should be unique

  card.innerHTML = `<img src="${img}${result.poster_path}">`
  cards.appendChild(card)

})
0
ответ дан Mister Lucky 16 January 2019 в 02:09
поделиться

Вы должны создать дочерний img для каждого значения tvSeriesImg:

var url = "https://api.themoviedb.org/3/tv/popular?api_key=YOURKEY&language=en-US&page=1";
var img  = "https://image.tmdb.org/t/p/w500"
var tvSeriesImg = [];

var request = new XMLHttpRequest();     // New instance of XMLHttpRequest
request.open('GET', url, true);         // Open the connection using the 'GET' Method
request.onload = function(){          // Create an onload function this is where the data is displayed on the webpage

var data = JSON.parse(this.response);    // Creating a data variable where our JSON is parsed and stored.

if(request.status >= 200 && request.status < 400){      // Check the request status.
    data.results.forEach(results => {                   //Looping through the JSON Array
        const popTvSeries = document.getElementById('tv-series-data');
        const popTvSeriesCard = document.createElement('div');
        popTvSeriesCard.setAttribute('id', 'card');
        popTvSeries.appendChild(popTvSeriesCard);

        tvSeriesImg.push(results.poster_path);

        //Get the first 6 items from the array!!
        console.log(tvSeriesImg.slice(0, 6));

        tvSeriesImg.slice(0, 6).forEach(x => {
            const tvImage = document.createElement('img');
            tvImage.src = img + x;
            tvImage.setAttribute('id', 'movieThumb');
            popTvSeriesCard.appendChild(tvImage);
        });
    });
}
}

request.send();  
0
ответ дан guijob 16 January 2019 в 02:09
поделиться

То, что вы делаете, очень запутанно, так как вы не можете увидеть сайт, на котором вы работаете, и протестировать код. Тем не менее, я думаю, что ваша проблема со второй половиной:

//Get the first 6 items from the array!!
        
        tvSeriesImg.push(results.poster_path);

        console.log(tvSeriesImg.slice(0, 6));


        const tvImage = document.createElement('img');
        tvImage.src = img + tvSeriesImg.slice(0, 6);
        tvImage.setAttribute('id', 'movieThumb');
        popTvSeriesCard.appendChild(tvImage);

Вы сохраняете пути в массиве, а затем в журнал консоли печатает первые 6 каждый раз, когда добавляет один, даже если их нет 6. Что немного сбивает с толку, но предполагается, что это код. Затем вы делаете

 tvImage.src = img + tvSeriesImg.slice(0, 6);

Это удалит первые 6 элементов из массива, каждый раз, когда он зацикливается и добавляет его к URL-адрес img, поэтому вы пытаетесь добавить в качестве источника URL-адрес, представляющий собой массив из 6 элементов. отсюда и ошибка. URL становится чем-то вроде http://img.com/absec.jpg,abb.jpg и т. д ...

Так как я не могу проверить его, так как у меня нет ключа API, возможно, есть ошибка, но ваш код должен выглядеть следующим образом:

var url = "https://api.themoviedb.org/3/tv/popular?api_key=f1d314280284e94ff7d1feeed7d44fdf&language=en-US&page=1";
var img = "https://image.tmdb.org/t/p/w500"
var tvSeriesImg = [];

var request = new XMLHttpRequest(); // New instance of XMLHttpRequest
request.open('GET', url, true); // Open the connection using the 'GET' Method
request.onload = function() { // Create an onload function this is where the data is displayed on the webpage

  var data = JSON.parse(this.response); // Creating a data variable where our JSON is parsed and stored.

  if (request.status >= 200 && request.status < 400) { // Check the request status.


    data.results.forEach(results => { //Looping through the JSON Array

      const popTvSeries = document.getElementById('tv-series-data');

      const popTvSeriesCard = document.createElement('div');
      popTvSeriesCard.setAttribute('id', 'card');
      popTvSeries.appendChild(popTvSeriesCard);

      tvSeriesImg.push(results.poster_path);

    });
    //remove from loop since you only want the top 6
    const tvImage = document.createElement('img');
    var first6Urls = tvSeriesImg.slice(0, 6);
    for (var i = 0; i < first6Urls.length; i++) {
      tvImage.src = img + first6Urls[i]
      tvImage.setAttribute('id', 'movieThumb' + i+1);
      popTvSeriesCard.appendChild(tvImage);
    }
  }
}
request.send();
[118 ]

По сути, вам нужно поместить код извлечения и добавления вне вашего для каждого цикла и добавлять их один за другим.

0
ответ дан samoan 16 January 2019 в 02:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: