liguofeng29’s blog

個人勉強用ブログだっす。

javascript - DHTML(documentオブジェクト、cookie使用)

javascript内のdocumentは、HTMLDocumentでもあり、DHTMLのオブジェクトでもある。

DHTMLのdocumentのメソッド

  • close()
  • open()
  • write()
  • writeln()

DHTMLのdocumentの属性

  • all
  • anchors
  • applets
  • cookie
  • documentElement
  • forms
  • frames
  • images
  • lastModified
  • links
  • location
  • referrer
  • scripts
  • styelSheets
  • title
  • URL

動的画面生成

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title> 動的に画面生成 </title>
</head>

<body>
    <script type="text/javascript">
        var n = 0;
        var win = null;
        // function
        var show = function(msg) {
            if ((win == null) || (win.closed)) {
                // open
                win = window.open("", "console", "width=340,height=220,resizable");
                // 出力
                win.document.open("text/html");
            }
            win.focus();
            win.document.writeln(msg);
        }
    </script>
    <input type="button" value="クリック" onclick="show('ボタンク:' + ++n + '回<br/>');">
</body>

</html>

f:id:liguofeng29:20160212233422g:plain

cookie使用

属性

  • max-age : 最大有効期間、秒単位
  • expires : 期限切れ
  • path : パス指定
  • domain : どのドメインの所属
  • secure :

例:1年有効 document.cookie = "name:sampe;max-age=" + (60 * 60 * 24 * 365) + ";domaint=sample.com" ;

cookie操作サンプル

<script type="text/javascript">
    // cookie設定
    function setCookie(name, value) {
        // 現在
        var expdate = new Date();
        // 1か月後
        expdate.setMonth(expdate.getMonth() + 1);
        // cookie追加
        document.cookie = name + "=" + escape(value); + "; expires=" + expdate.toGMTString() + ";";
    }

    // cookie取得
    function getCookie(name) {
        // cookie開始位置
        var offset = document.cookie.indexOf(name)
            // cookieあり
        if (offset != -1) {
            // 開始位置
            offset += name.length + 1;
            // 終了位置
            end = document.cookie.indexOf(";", offset);
            // 最後
            if (end == -1) {
                end = document.cookie.length;
            }
            // 取得
            return unescape(document.cookie.substring(offset, end));
        } else {
            return "";
        }
    }
    setCookie("user", "google.com");
    alert(getCookie("user"));
</script>