LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Thursday, January 18, 2018

HTML要素を動的に作りたい(ハイパーリンク)

JavaScriptでハイパーリンクを動的に作る


このようなリンクを作成するコードの例です




コード.gs
function doGet(){
 return HtmlService.createHtmlOutputFromFile('index'); 
}
意訳
この処理は以下を実行する
指定したHTMLファイルを表示する




index.html
<!DOCTYPE html>
<html>
<body>
  <div id="main_div">
  </div>
</body>
<script>
  var sites = [
    ["Google検索", "https://www.google.co.jp/"],
    ["Youtube", "https://www.youtube.com/"],
    ["Gmail", "https://mail.google.com/"]
  ]
  
  create_link();
  function create_link() {
    var main_div = document.getElementById("main_div");
    for (var i = 0; i < sites.length; i++) {
      var link = document.createElement("a");
      var id = "link_" + i;
      link.textContent = sites[i][0] + " / ";
      link.setAttribute("id", id);
      link.setAttribute("href", sites[i][1]);
      main_div.appendChild(link);
    }
  }
</script>
</html>
意訳
これはHTML5文書です


divを置く(idはmain_div)



サイト名とURLのデータを用意しておく





create_link()を実行する
この処理は以下の処理を実行する
idがmain_divの要素を取得する
以下の処理を3回繰り返す
aタグを作成する
idを決める
sitesのi番目の0番目をテキスト表示する(サイト名)
idを設定して
sitesのi番目の1番目をhrefに設定する(サイトURL)
main_divに追加する






index.htmlにある

var sites = [] の 中身 を増やすと作成されるリンクの数が変わります


サイト名とURLのデータを配列ではなくオブジェクトで作ってみる


index.html
<!DOCTYPE html>
<html>
<body>
  <div id="main_div">
  </div>
</body>
<script>
  var data = {
    0: {
      "name": "Google検索",
      "url": "https://www.google.co.jp/"
    },
    1: {
      "name": "Youtube",
      "url": "https://www.youtube.com/"
    },
    2: {
      "name": "Gmail",
      "url": "https://mail.google.com/"
    }
  }

  create_link();
  function create_link() {
    var main_div = document.getElementById("main_div");
    for (var i = 0; i < 3; i++) {
      var link = document.createElement("a");
      var id = "link_" + i;
      link.innerHTML = data[i]["name"] + " / ";
      link.setAttribute("id", id);
      link.setAttribute("href", data[i]["url"]);
      main_div.appendChild(link);
    }
  }
</script>
</html>



参考

HTML Service: Create and Serve HTML
https://developers.google.com/apps-script/guides/html/

Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...