未捕获的ReferenceError:未定义变量

时间:2018-07-25 06:17:59

标签: javascript html google-api

我在网站上有一个按钮,当单击该按钮时,它将执行以下功能getAccountsToPanel。该函数调用已登录用户的可用Google Tagmanager帐户,并将其放入面板中。该函数是外部javascript文件gtm_api_handling.js

的一部分
var accounts;
var accountClicks = 0;
var accountButtons ="";
function getAccountsToPanel() {
   if (accountClicks == 0) {
     var request = gapi.client.request({"method":"GET", ath":"tagmanager/v2/accounts"});
     request.then(function(response){accounts = response.result.account});
     accounts.forEach(function(elem){accountButtons += `<button class="accordion">Account: ${JSON.stringify(elem.name)}</button>`;})
     var x = document.getElementById("accountPanel");
     x.innerHTML = accountButtons;
     accountClicks = 1; // make sure this function is not doing anything again after its first execution
   }
}

但是,在第一次单击此按钮时,我收到错误消息:

gtm_api_handling.js:147 Uncaught TypeError: Cannot read property 'forEach' of undefined
    at getAccountsToPanel (gtm_api_handling.js:147) // this is line that begins with accounts.forEach in the above function
    at HTMLButtonElement.onclick (page2.html:52) // this is the buttons position on the main html sheet

如果然后我进入控制台并查看“帐户”的内容,或者再次单击该按钮(重新运行该功能),则所有操作都将与我期望的一样。

以前有人看过吗?您有解决办法吗?

1 个答案:

答案 0 :(得分:0)

参考Google API Client Library,似乎您需要将forEach放入then回调函数中。这样的事情可能会起作用:

var accounts;
var accountClicks = 0;
var accountButtons ="";
function getAccountsToPanel() {
   if (accountClicks == 0) {
     var request = gapi.client.request({"method":"GET", "ath":"tagmanager/v2/accounts"});
     request.then(function(response) {
         accounts = response.result.account;
         accounts.forEach(function(elem){accountButtons += `<button class="accordion">Account: ${JSON.stringify(elem.name)}</button>`;})
         var x = document.getElementById("accountPanel");
         x.innerHTML = accountButtons;
     });
     accountClicks = 1; // make sure this function is not doing anything again after its first execution
   }
}