首页 > 解决方案 > 如何保持状态不断出现在 JavaScript 函数到 HTML

问题描述

这是我在这个论坛上提出的上一个问题的延续。

我通过添加 else 条件对代码进行了一些更改。我想要解决的是在页面加载时显示当前状态。当前代码仅在单击按钮时才显示状态。

如何在页面加载时显示当前状态,并在单击按钮时更新状态。

代码.GS

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function checkStatus(notify) { 
  var employee = "John Peter";
  var ss = SpreadsheetApp.getActiveSpreadsheet();        
  var mainSheet = ss.getSheetByName("MAIN");
  var data = mainSheet.getDataRange().getValues();
  
  for (var j = 0; j < data.length; j++){
    var row = data[j];
    var mainSheet2 = row[4];
    var mainSheet3 = row[0];
    var status = (mainSheet2 =="IN" && mainSheet3 == employee) ; 
    if (status == true){
      var notify = employee +" You Are In"
      return notify;
      }
    else{
     var status = (mainSheet2 =="OUT" && mainSheet3 == employee) ; 
    if (status == true){
      var notify2 = employee +" You Are Out"
      return notify2;
  }
}
  }
}

索引.html

<body>
    <div>
      <button onclick="onStatus()">Check Status</button>
      <font color='Green' id="status" onbeforeprint="onStatus" ></font>
      </div>
      
    

    <script>
      function onStatus() {
        google.script.run.withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
          .checkStatus(); // Call the backend function
      }

      function updateStatus(notify) {
        document.getElementById('status').innerHTML= notify;
      }
      
     
      
    </script>
  </body>

标签: javascripthtmlgoogle-apps-scriptweb-applications

解决方案


您可以在页面加载时调用此函数,如下所示。然后在您的正文标签结束之前添加此脚本。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
    // The code in this function runs when the page is loaded.
    $(function() {
     google.script.run.withSuccessHandler(updateStatus)
              .checkStatus(); 
    });
</script>

推荐阅读