for循环不返回第一个元素,但返回其他元素

时间:2019-03-13 16:52:44

标签: javascript for-loop

For循环不会返回来自json对象的第一个元素,但会返回其他元素。我想返回 json对象中的所有'id'属性。我认为我所做的一切都正确。有什么问题吗?

[
  {
    "dataTarget": "tempero-restaurante",
    "modalTitle": "Tempero Restaurante",
    "url": "../img/1.jpg",
    "id": "tempero-restaurante"
  },
  {
    "dataTarget": "aksam-gunesi",
    "modalTitle": "Akşam Güneşi",
    "url": "../img/2.jpg",
    "id": "aksam-gunesi"
  }
]

$(document).ready(() => {
  let proje = document.querySelectorAll(".proje");
  let kapsayici = document.querySelector("#proje-kapsayici");
  let modal = document.createElement("div");

  class Requests {
    get(url) {
      return new Promise((resolve, reject) => {
        fetch(url)
          .then(res => res.json())
          .then(data => resolve(data))
          .catch(err => reject(err));
      });
    }

    projectProps(idName) {
      Object.assign(modal, {
        idName: idName,
        className: "modal fade"
      });
      modal.setAttribute("tabindex", "-1");
      modal.setAttribute("role", "dialog");
      modal.setAttribute("aria-labelledby", "exampleModalLabel");
      modal.setAttribute("aria-hidden", true);
    }
  }
  const rq = new Requests();

  proje.forEach((item, index) => {
    rq.get("../json/portfolyo.json").then(data => {
      proje[index].setAttribute("data-target", data[index].dataTarget);
    });
  });
});

1 个答案:

答案 0 :(得分:0)

$(document).ready(() => {
  let proje = document.querySelectorAll(".proje");
  let kapsayici = document.querySelector("#proje-kapsayici");
  let modal = document.createElement("div");

  class Requests {
    get(url) {
      return new Promise((resolve, reject) => {
        fetch(url)
          .then(res => res.json())
          .then(data => resolve(data))
          .catch(err => reject(err));
      });
    }

    projectProps(idName) {
      Object.assign(modal, {
        idName: idName,
        className: "modal fade"
      });
      modal.setAttribute("tabindex", "-1");
      modal.setAttribute("role", "dialog");
      modal.setAttribute("aria-labelledby", "exampleModalLabel");
      modal.setAttribute("aria-hidden", true);
    }
  }
  const rq = new Requests();

  rq.get("../json/portfolyo.json").then(data => {
    data.forEach((item, index) => {
      proje[index].setAttribute("data-target", item.dataTarget);
    });
  });
});