【问题标题】:How to get the index of the selected item in a list box?如何获取列表框中所选项目的索引?
【发布时间】:2012-08-03 22:23:07
【问题描述】:

我想在 Google Apps 脚本列表框中获取所选项目的索引,而不是所选项目本身。到目前为止,我看到的所有示例都创建了一个服务器处理程序,该处理程序通过

获取列表框的值
var list1Value = e.parameter.list1;

我想获取索引,以便可以索引到数组中。我尝试使用此解决方案 http://productforums.google.com/forum/#!category-topic/apps-script/services/vXa57-9T6E4 但我的脚本抱怨 indexOf 未被识别

var currentmonth = months.indexOf(e.parameter.list1);

有人知道如何获取索引吗?顺便说一句,这是一个在站点中而不是在电子表格中运行的谷歌应用程序脚本,如果这会有所不同的话。

【问题讨论】:

  • 脚本中的months 是什么?
  • 我有一个电子表格,我要从中提取几个月。这只是标准的一月、二月
  • var phoneBillSpreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID); var sheets = phoneBillSpreadsheet.getSheets(); months = sheets[0].getRange(1, 2, 1, 11).getValues(); phoneBillData = sheet[0].getRange(3, 2, 6, 11).getValues();`
  • 你必须知道 getValues() 返回一个二维数组,你必须使用它的“简单”数组部分才能使用 indexOf()。在您的示例中,它将是 month[0],但我想您知道 ;-)
  • 是的,我昨晚想出了实现另一个功能。不过感谢您的提醒。像我这样的新手可以使用我能得到的所有帮助。

标签: javascript google-apps-script google-sites


【解决方案1】:

另一个答案没有多大意义,因为 Google Apps 脚本是在 Google 的服务器上执行的,而不是在您的浏览器中,并且 indexOf() 在 GAS 中得到很好的识别。

您应该使用一个包含列表框元素的数组,然后使用listArray.indexOf(listelement); 您将获得所选项目的索引。

示例:

//in the UI construction 

var ItemlistArray = ['item1','item2','item3','item4'];// note that this variable definition could be placed outside of the function so it becomes a global variable...
for (n=0,n<ItemlistArray.length;++n){
ListBox.addItem(ItemlistArray[n]
}

//in the Handler function

var item = e.parameter.listBoxName
var ItemlistArray = ['item1','item2','item3','item4'];// if ItemlistArray is global this line can be removed
var index = ItemlistArray.indexOf(item); // if for example the selected item was 'item3', index will be 2

【讨论】:

  • 能否请您详细说明UI构建部分?您不会使用“选择单元格”→验证→标准→项目列表来构建项目列表。
  • 抱歉,我无法访问我的电脑...我在 Holliday's 但很快就会回来:)
猜你喜欢
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 2019-01-25
  • 2011-06-18
相关资源
最近更新 更多