在列表中插入项目

时间:2018-05-18 01:45:58

标签: google-apps-script google-docs

我在我的文档中搜索一个占位符,该占位符是一个列表项(例如body.findText('{{list}}')。我有一系列要插入此列表的项目。

一旦我有了listItem元素,我该如何向它添加更多listItems?我希望有类似foundListItem.getParent().appendListItem(items[i])

的东西

我已经搜索了这个问题的答案,并且看到了一些需要一些艰巨的努力才能完成的答案。 必须是一种更简单的方法!例如,将它们附加到底部并确定将其移动到哪里是一个荒谬的答案。

2 个答案:

答案 0 :(得分:1)

这看起来很麻烦,列表由ListItems组成,但似乎没有List对象。有一个ListId,但它似乎没有任何实际功能,除了你可以拆分列表并继续数字。您似乎只能向主体添加ListItem,但似乎没有一种简单的方法来获取ListItem的索引,以便您可以在它之后追加。

我编写了一个函数,它将遍历正文中的所有项,以查找带有一些占位符文本的ListItem并返回其索引。

function findListItemWithText(text) {

  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var index = -1;

  for (var i=0; i<body.getNumChildren(); i++) {
    var child = body.getChild(i);

    if (child.getType() ==  DocumentApp.ElementType.LIST_ITEM) {

      var listItem = child.asListItem();
      if (listItem.getText() == text) {
         index = i;
      }
    }
  }
  return index;
}

然后我编写了一个函数,它将ListItem替换为数组中的元素:

function replaceListItem (placeholder, list) {

  var index = findListItemWithText(placeholder);
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();

  var listItem = body.getChild(index).asListItem();

  // replace the text in the placeholder ListItem
  listItem.setText(list[0]);

  // append the rest of the list after the placeholder ListItem
  for (var i=1; i<list.length; i++) {
    body.insertListItem(index + i, list[i]);  
  }
}

然后,您可以使用占位符和列表调用此函数,如果有一个带有此文本的ListItem,它将在该点附加ListItems列表。

replaceListItem("{{list}}", ["One", "Two", "Three"]);

适用于编号列表和项目符号列表。如果有两个或更多占位符,它将只替换最后一个占位符。

如果有人可以批评这一点,我会有兴趣听到更有效的方法来查找和操纵给定的元素,因为看起来我的解决方案比我预期的要多得多。

答案 1 :(得分:0)

我能够使用以下代码实现所需的行为:

function updateList(){
  var listItem = DocumentApp.getActiveDocument().getBody().getListItems()[0]
  var list = listItem.getParent()
  var index = list.getChildIndex(listItem)
  debug && Logger.log('ListItem ['+index+'] parent: '+list.getType()) // debug=true logging

  // remove listItem
  list.removeChild(listItem)

  // add new children
  var names = getList() // function retrieves a list of rows from spreadsheet.
  names.forEach(function (v){
    list.insertListItem(index++, v[1]) // the second element is the name
  })
}

请注意,使用模板字符串,这次对我来说没问题;但是,要找到模板字符串&#39; {{list}}&#39;并用我发现的数据替换它:

function findListItem(str) {
  if (str == undefined) str = '{{list}}'
  debug && Logger.log(str)
  var a = ['one', 'two', 'three']
  var body = DocumentApp.getActiveDocument().getBody()
  var match = body.findText(str)
  if (match == null) {
    debug && Logger.log('No match')
    return
  }
  var listItem = match.getElement().getParent()
  var list = listItem.getParent()
  var idx = list.getChildIndex(listItem)
  listItem.removeFromParent()
  a.forEach(function(s) {
    list.insertListItem(idx++, s)
  })
}
相关问题