跳轉到內容

使用 Google Apps 指令碼開發 Web 應用程式/響應使用者

來自華夏公益教科書

用於使用者介面的 JavaScript

[編輯 | 編輯原始碼]

本書重點介紹如何利用您的 Google 帳戶建立資料驅動的 Web 應用程式。它不會過多介紹如何建立您的使用者介面。在本節中,我將提供一些簡單的示例,其中一些甚至不遵循最佳實踐,但它們是您可以嘗試的一些快速簡便的方法,用於驗證某些原理。

使用者點選某些內容

[編輯 | 編輯原始碼]

HTML 中幾乎所有元素都可以新增 onClick 函式。這包括

  • 按鈕
  • 文字(最容易使用 span 標籤完成)
  • 列表項

onClick 通常不被認為是正確的方法,但如果您確定這是使用者互動時該元素唯一要執行的操作,那麼它可以為您工作。[1]

以下是一些簡單的 HTML/JavaScript 程式碼,當用戶按下按鈕時,會開啟一個顯示“您點選了我”的警報框

<button type="button" onClick="openAlert('press me')">press me</button> <!-- note the use of both types of quotes -->

<script>
function openAlert(text){
   alert(text);
   }
</script>

更新頁面上的某些文字

[編輯 | 編輯原始碼]

警報框很煩人,不要使用它們。相反,讓使用者的操作改變頁面上的內容。以下是上一個示例的更新版本,現在按下按鈕會在按鈕下方頁面上新增一些文字

<button type="button" onClick="openAlert('press me')">press me</button> <!-- note the use of both types of quotes -->
<div id='emptyatfirst'></div>

<script>
function openAlert(text){
   document.getElementById('emptyatfirst').innerHTML=text;
   }
</script>

如果您計劃對 div 內的文字進行大量更改,您可能需要建立一個全域性變數,如下所示:[2]

<button type="button" onClick="openAlert('press me')">press me</button> <!-- note the use of both types of quotes -->
<div id='emptyatfirst'></div>

<script>
// here's a global variable:
var emptyatfirst=document.getElementById('emptyatfirst');
function openAlert(text){
   emptyatfirst.innerHTML=text; // this uses the global variable
   }
</script>
  1. 正確的方法是 element.addEventListener('click', function() { /* 在此處執行操作*/ }, false);
  2. 請注意,即使您認為這可以節省您以後的輸入,您也不能執行 var emptyatfirst=document.getElementById('emptyatfirst').innerHTML;
華夏公益教科書