使用复选框和按钮向文档添加文本?

时间:2018-12-20 23:57:13

标签: google-apps-script google-docs

我正在为Google docs(类似单词)创建一个应用脚本加载项,我创建了一个带有复选框和按钮的侧边栏,并希望在单击按钮后并根据具体情况将特定文本打印到文档中突出显示的复选框,到目前为止,我设法用Html组件创建了侧边栏,但是我无法管理文档中的文本。

<link href="https://ssl.gstatic.com/docs/script/css/add-ons.css"      rel="stylesheet">
<div class="sidebar">
     <div class="elements">
        <input type="checkbox" id="myCheck1">Check Box 1<br>
        <input type="checkbox" id="myCheck2">Check Box 2<br><br>
        <button class="blue" id="process" onclick="myFunction()">Print</button><br><br>
    <p id="text1" style="display:none">Checkbox1 is CHECKED!</p>
    <p id="text2" style="display:none">Checkbox2 is CHECKED!</p>
    </div>
</div>
<script>
function myFunction() {
   var checkBox1 = document.getElementById("myCheck1");
   var checkBox2 = document.getElementById("myCheck2");
   var text = document.getElementById("text1");
   var text = document.getElementById("text2");
   if (checkBox1.checked == true){
      text1.style.display = "block";
      } else {
      text1.style.display = "none";
      }
   if (checkBox2.checked == true){
      text2.style.display = "block";
      } else {
      text2.style.display = "none";
      }
   }
</script>

这是我在侧边栏上使用的HTML,并尝试了一个我在网上找到的示例来打印文本,但这将在侧边栏上将文本打印在按钮上,而不是在文档上。

function onInstall() {
  onOpen();
}
function onOpen() {

  DocumentApp.getUi()
  .createAddonMenu() // Add a new option in the Google Docs Add-ons Menu
  .addItem("KO Addon", "showSidebar")
  .addToUi();  // Run the showSidebar function when someone clicks the menu
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile("KO")
    .evaluate()
    .setTitle("KO Addon Options"); // The title shows in the sidebar
  DocumentApp.getUi().showSidebar(html);
}

这是将侧栏添加到文档中的主要代码,我只能使用文档上的代码在文档上打印内容,但是我只是不知道如何使它们协同工作,任何帮助都是非常感谢,

谢谢。

1 个答案:

答案 0 :(得分:0)

  • 您要将从HTML端检索到的值放入Google Document。

如果我对您的问题的理解是正确的,那么该样本如何?就您而言,当HTML方的值发送到Google Apps脚本时,您可以使用google.script.run来实现。

示例脚本:

HTML面:

请在myFunction()的HTML末尾添加以下脚本。

google.script.run.putValues({checkBox1: checkBox1.checked, checkBox2: checkBox2.checked});
气体侧:

请在Google Apps脚本中添加以下功能。

function putValues(obj) {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph(JSON.stringify(obj));
}

注意:

  • 在此示例中,它假设您的脚本在Google文档上显示了侧边栏,并且工作正常。
  • 修改脚本后,请打开侧栏。单击按钮后,复选框的值将发送到Google Apps脚本,并将其值放入活动文档中。
  • 这是一个简单的示例脚本。因此,请根据您的情况进行修改。

参考文献:

如果我误解了您的问题,请告诉我。我想修改它。