繁体   English   中英

我不明白为什么我的全局变量没有更新?

[英]I don't understand why my global variable isn't updating?

我昨天发布了这个,但我仍然傻眼了。 我似乎无法弄清楚这个问题。 我想在用户单击状态SVG时使用stateName变量的新值更新parkEndpoint URL。 它一直是第1行的原始值。

我试过在控制台中查找并且在函数getStateName运行之后它确实更新了stateName变量,但是当我在该函数运行后控制台登录parkEndpoint变量时,它仍然显示旧变量,我只是设置为空。

var stateName = "";
const alertEndpoint = ("https://developer.nps.gov/api/v1/alerts? 
&limit=400&api_key=" + apikey );
var parkEndpoint = ("https://developer.nps.gov/api/v1/parks? 
stateCode=" + stateName + "&limit=100&api_key=" + apikey);

const elements = document.querySelectorAll('path');
console.log(elements);

// add event listeners
elements.forEach(function(el) {
  el.addEventListener("click",  getStateName);

});


   function getStateName(nodeList){
   stateName = nodeList.path[0].id;
   outputStateName(stateName);

 }

   function outputStateName(stateName) {
   console.log(stateName);
   console.log(parkEndpoint);
  }

我只是想让它更新URL中的stateName变量。

这是因为你没有更新parkEndpoint的值

在javascript中,字符串通过引用存储。 含义parkEndpoint引用定义为L3的字符串,以后不再重新分配。

您需要在getStateName函数中重新分配它。

您的statName变量在开头是空的,甚至在从stateName = nodeList.path[0].id;获取状态名称之后stateName = nodeList.path[0].id; 变量parkEndpoint永远不会被更新。

var stateName = '';
var parkEndpoint = parkEndpointUpdate();

function parkEndpointUpdate(){
   return `https://developer.nps.gov/api/v1/parks?
   stateCode=${stateName}&limit=100&api_key=${apikey}`
}

function getStateName(){
   stateName = nodeList.path[0].id;
   parkEndpoint = parkEndpointUpdate(); // This func will updated your variable of parkEndPont
   outputStateName(stateName);
}

暂无
暂无

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

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