简体   繁体   English

如何在动态变量中使用“ document.getElementById”?

[英]How to use “document.getElementById” with dynamic var?

I have the following code, as user "no-deps" gave to me.... As general idea, I want to get information from a variable with latitude and longitude of a poi in google maps, getting in a second variable information about name of place with specific map coordinates. 我有以下代码,就像用户“ no-deps”给我的一样。...作为一般的想法,我想从具有Google地图中poi的经度和纬度的变量中获取信息,获取有关具有特定地图坐标的地点名称。

The problem is that the code works as good as return the value of poi but this is happened in the first only div in json process. 问题在于代码的工作原理与返回poi的值一样好,但这发生在json进程的第一个唯一div中。

I think that with a way must defive with a dynamic value the referred variable of document.getElementById() and as second step to define <div id="'+postid+'"></div> with the same dynamic variable... 我认为以某种方式必须用动态值来抵抗document.getElementById()的引用变量,并作为第二步来定义具有相同动态变量的<div id="'+postid+'"></div> ...

I've tried but this as I did has no result..... 我已经尝试过,但是像我一样没有结果.....

The code is the following: 代码如下:

<script type='text/javascript'>
        //<![CDATA[ 
function favouritePosts(json) {
var post_id;
var Lat_long;               // dynamic var with lang and lat information

fetch('https://open.mapquestapi.com/geocoding/v1/reverse?key=jzZATD7kJkfHQOIAXr2Gu0iG62EqMkRO&location='+Lat_long+'')
        .then((data) => {
            return data.json();
        })
        .then((json) => {
                const result = json.results[0].locations[0];
          document.getElementById("output").innerHTML= result.street&","&result.postalCode;
        })
        .catch((err) => {
            console.log(err);
        });
var item = '<div id="'+postid+'"></div>';
        document.write(item);
        }
}
 //]]>
 </script>

The first thing you should know is that Javascript is single-threaded. 您应该知道的第一件事是Javascript是单线程的。

Since it's single-threaded, it can only do one thing at a time. 由于它是单线程的,因此一次只能做一件事。

To prevent the brower blocks on the code' execution, which makes more time to do such as the http request, the brower provides the web apis. 为了防止浏览器块阻止代码执行,这会浪费更多时间(例如http请求),浏览器提供了Web api。

The web apis has asynchronous methods can prevent blocking. Web API具有异步方法可以防止阻塞。 When all the synchronous code is completed, the asynchronous method's callback function can execute. 当所有同步代码完成后,异步方法的回调函数即可执行。

Back to your situation, function Fetch is a asynchronous method. 回到您的情况,函数Fetch是一个异步方法。 You can only get the json data in the callback function because the callback function is executed after your synchronous code, which is your last line code pasted on the question description. 您只能在回调函数中获取json数据,因为回调函数是在您的同步代码之后执行的,这是您粘贴在问题描述上的最后一行代码。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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