我刚接触Google Appscript和Javascript HTML。我正在开发一个使用google.script.run接收数组的web应用程序,它可以正常工作,但似乎只能访问接收函数中的变量。
我的问题是,有什么办法可以从Code.gs接收变量并将其设置为全局变量? HTML:
<html>
<head>
<body>
<div id="variables">
<input id="state">State</input>
<input id="equity-spread">Equity</input>
<input id="age-spread">Age</input>
<input id="distance">Distance</input>
</div>
<div id="letter">
<button>a</button>
<button>b</button>
<button>c</button>
<button>d</button>
<button>e</button>
<button>f</button>
<button>g</button>
<button>h</button>
<button>i</button>
</div>
<div>
</div>
</body>
</head>
</html>
index.js
function formClicked(){
var state = document.getElementById("state").value
var equity = document.getElementById("equity-spread").value
var age = document.getElementById("age-spread").value
var distance = document.getElementById("distance").value
//this function is only to capture and send user input to the server-side Code.gs
google.script.run.withSuccessHandler(displayAnalysis).analysis(state,equity,age,distance)
}
document.getElementById("letter").addEventListener("click", checkInput);
Code.gs
function analysis(STATE,EQUITY,AGE,DIST){
//spreadsheet analysis code here
var results = [a,b,c,d]
return results
index.js
function displayAnalysis(items){
console.log(items) //this correctly displays the [a,b,c,d] array
//additional code that modifies the array
}
function checkInput(e){
//I created this function because I need the event listener and I couldn't find a way to insert an event listener on the displayAnalysis()
//I need to access the "items" variable here, but can't figure out how
var input = e.target.closest("button").innerHTML
console.log(input)
var result = items.indexOf(input)
//I can't do indexOf because "items" is undefined
//I need to evaluate the selected value from the array that was sent over from Code.gs
var original = items //this produces an undefined
}
基本上,我需要在var items
和displayAnalysis()
函数中都使用checkInput
来评估从Code.gs发送的数组中是否找到了选定的值。
由于尝试读取可以公开“读取”变量的位置,因此我尝试设置设置var _data = items
。我也将displayAnalyis函数重写为这样的全局变量:
var publicVar = function displayAnalysis(items)
//this also doesn't work
最后,我还尝试将事件监听器和“ items”变量放在相同的函数中,例如(这将是最佳解决方案):
function formClicked(){
var state = document.getElementById("state").value
var equity = document.getElementById("equity-spread").value
var age = document.getElementById("age-spread").value
var distance = document.getElementById("distance").value
google.script.run.withSuccessHandler(displayAnalysis).analysis(state,equity,age,distance)
}
document.getElementById("letter").addEventListener("click", displayAnalysis);
function displayAnalysis (e,items)
//console returns "e" as undefined. The first parameter is always defined even if switched
//this would be the ideal solution because I can receive the "items" and evaluate the "event(e)" together in the same function, but I can't get this to work either.
我觉得这是一个容易解决的问题,但我似乎无法找出我做错了什么。在这个问题上的任何帮助将不胜感激。