2015-07-03 31 views
1

基本上剪切和粘貼元素: 這些都是有效的命令,谷歌文檔(與GApps腳本)命令插入元素而不知道它的類型?

{ 
    var doc = DocumentApp.getActiveDocument(); 
    var body = doc.getBody(); 
    var N = [some number]//the element to copy 
    var elementVar = body.getChild(N) 
    if (element.getType = 'LIST_ITEM') 
    { 
     body.appendListItem(elementVar.copy());//copy is required 
    } 
    //replace XXX_XXX below with one of about a dozen available types. 
    if (element.getType = 'XXX_XXX') 
    { 
     body.appendXxxXxx(elementVar.copy()); 
    } 
    //etc. 
} 

但是如果你想不知道它的類型,而無需使用一堆if語句來插入一個元素是什麼?

{ 
    ... 
    body.appendElement(elementVar.copy());//error 
} 
+0

你如何創建(或獲得)這些元素? –

+0

serge - check編輯 – Michael

+0

不幸的是,我認爲除了「if」或「case select」方法之外別無選擇,我同意它有點乏味;-) –

回答

0

考慮映射出可能的功能在手前的對象...

var map = { 
    'LIST_ITEM' : function(copy) { body.appendListItem(copy); }, 
    'PARAGRAPH' : function(copy) { body.appendParagraph(copy); } 
}; 

var child = body.getChild(N); 
var copy = child.copy(); 

// pass copy to corresponding append func based on type 
map[child.getType()](copy); 
相關問題