简体   繁体   中英

How to show element from function which returns array in Javascript

So I should get announcement's i element's x. In the end of the code, I've added loop which have to set left and top properties to the pin. Please help me:) Here is my code:

    var announcement = function () {
      var result = [];

      for (var i = 0; i < 8; i++) {
        result.push({
          "location": {
            "x": Math.floor(Math.random() * 1200) + 1,
            "y": Math.floor(Math.random() * (630 - 130) ) + 130
          }
        })
      }

      return result;
    }

    var map = document.querySelector(".map");
    var pinTemplate = document.querySelector("#pin").content.querySelector(".map__pin");        

    for (var i = 0; i < announcement().length - 1; i++) {
      var pin = pinTemplate.cloneNode(true);
      pin.setAttribute("style", "left: " + announcement()[i].x + "top: " + announcement()[i].y);
      document.querySelector(".map__pins").appendChild(pin);

      console.log(announcement()[i].x);
    }

Try this:

You can do like this to get element and display in div or any element you want.

Please see the working example.

 var announcement = function () { var result = []; for (var i = 0; i < 8; i++) { result.push({ "location": { "x": Math.floor(Math.random() * 1200) + 1, "y": Math.floor(Math.random() * (630 - 130) ) + 130 } }) } return result; } var node = document.createElement("div"); announcement().forEach(function (element) { var textnode = document.createTextNode('left: '+element.location.x+' - top: '+element.location.y+' '); node.appendChild(textnode); document.getElementById("myList").appendChild(node); })
 <div id="myList"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM