在示例代码中:
HTML(索引):
<form>
<br><br>
Name:
<br>
<input type="text" name="name">
<br><br>
Comments:
<br>
<input type="text" id="comments">
<br><br>
<input type="button" id="button" value="Submit Info" onclick="google.script.run
.testFunction(this.form)">
</form>
代码:
function doGet() {//Creates the webpage
return HtmlService.createTemplateFromFile('Index')//From the GUI file.
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function testFunction(form){
Logger.log(form.name);//Works when using the 'name' of the element.
Logger.log(form.comments);//Does not work when using the 'ID'.
}
为什么在添加HTML值的“名称”而不是“ ID”时返回一个值?如果我想通过ID获取值,我该怎么做呢?我试过了:
form.getElementById("comments");
但这只会给我带来一个错误,老实说,在那之后我就没了主意。
注意:使用“名称”字段对我来说是完全可以接受的,就像我一直在做的那样,我只是好奇我正在整理HTML。
我相信Google在幕后所做的就是将提取form
出来的内容作为HTML表单并将其发送回服务器。HTML表单使用该name
属性存储发送回服务器时的所有名称名称对。因此,如果这是对此表格的获取请求:
<form>
<input type="text" name="field1" value="value1"/>
<input type="text" name="field2" value="value2"/>
</form>
它看起来像?field1=value1&field2=value2
。
因此,在Code.gs的服务器端,您基本上是将其作为一个对象(不是DOM对象)获得,这就是为什么您form.getElementById("comments");
无法使用的原因。
无论哪种方式,带有<input>
标签的标准都是使用该name
属性,因此您应该坚持使用它。id
仅当您需要在客户端javascript中查找值时,才应使用该属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句