我第一次在谷歌檔案中使用谷歌應用程式腳本,并試圖檢索檔案中的所有文本,直到游標位置。
我的想法是在游標之前迭代段落并將段落文本附加到一個空陣列,但我很難找到游標段落索引。但也許我的整個方法是有偏差的,所以任何關于如何實作這一點的想法都值得贊賞。
function getText() {
const document = DocumentApp.getActiveDocument();
const cursor = document.getCursor();
const paragraphs = document.getBody().getParagraphs();
const index = paragraphs.indexOf(cursor.getElement()); // fails to find the index of the cursor paragraph
const selectedParagraphs = paragraphs.slice(0, index);
const text = [];
for (let i = 0; i < selectedParagraphs.length; i ) {
text.push(selectedParagraphs[i].getText());
}
// add the text of the cursor's element up until the cursor's position
const cursorOffset = cursor.getOffset();
const cursorText = cursor.getElement().asText().getText();
text.push(cursorText.substring(0, cursorOffset));
return text.join('\n');
uj5u.com熱心網友回復:
在您的腳本中,如何進行以下修改?
從:
const index = paragraphs.indexOf(cursor.getElement());
至:
const e = cursor.getElement();
const index = document.getBody().getChildIndex(e.getType() == DocumentApp.ElementType.PARAGRAPH ? e : e.getParent());
- 在這種情況下,使用Class Body 的方法
index檢索。getChildIndex
參考:
- getChildIndex(子)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529455.html
