LoginSignup
1
1

More than 3 years have passed since last update.

snippet: JavaScript

Last updated at Posted at 2015-05-30

右クリック禁止

<body onContextMenu="return false;">
...
</body>

元の関数を上書き、デフォルト引数

var parseInt_original = parseInt_original || parseInt;
// 第二引数がなければ10を指定したい
var parseInt = function(strNum, base) {
  // 引数が省略されていた場合undefinedになる。
  var base = typeof base !== 'undefined' ?  base : 10;
  return parseInt_original(strNum, base);
};

parseInt('0x20');
var parseInt_original = parseInt_original || parseInt;
var parseInt = function(strNum, base) {
  // strNum = '0x20' が0になってしまうので判定追加
  if (typeof value === 'string') {
      return parseInt_original(strNum);
  }
  var base = typeof base !== 'undefined' ?  base : 10;
  return parseInt_original(strNum, base);
};

parseInt('0x20');

戻るで戻った時もonloadを実行させる

window.onunload = function() {};

radioから値取得

値取得
var e = document.getElementsByName("numbers");
for ( i = 0; i < e.length; i++ ) {
    if ( e[i].checked ) {
        console.log(e[i].value);
    }
}
チェック
var e = document.getElementsByName("numbers");
for(var i=0; i<e.length; i++) {
    if("2" == e[i].value) {
        e[i].checked = "on";
    }
}

HTMLBRElement は IE8以降対応

javascript 1.8

onloadに処理を追加する

if (window.addEventListener) { //for W3C DOM
  window.addEventListener("load", initOther, false);
} else if (window.attachEvent) { //for IE
  window.attachEvent("onload", initOther);
} else  {
  window.onload = initOther;
}

式クロージャー

今まで
var hoge = function(x) {return x*x;}(3);
console.log(hoge);//9
式クロージャーを使う場合(中括弧とreturnが省略できる)
var hoge = (function(x)x*x)(3);
console.log(hoge); //9

javascript 1.7

yield

<script type="text/javascript; version=1.7" src="xxxx.js"></script>
<script type="text/javascript; version=1.7">
function test() {
  yield 'hoge';
  yield 'fuga';
  yield 'piyo';
}

var generator = test();
alert(generator.next()); //hoge
alert(generator.next()); //fuga
alert(generator.next()); //piyo
alert(generator.next()); //uncaught exception: [object StopIteration]
</script>

let

letが無い場合、すべて6が出力される。
var list = document.getElementById("list");
var i;
for (i = 1; i <= 5; i++) {
    var item = document.createElement("li");
    item.appendChild(document.createTextNode("Item " + i));
    //let (j = i) {
        item.onclick = function (ev) {
            console.log("Item " + i + " is clicked.");
        };
    //}
    list.appendChild(item);
}
letを使う場合、1〜5が出力される。
var list = document.getElementById("list");
var i;
for (i = 1; i <= 5; i++) {
    var item = document.createElement("li");
    item.appendChild(document.createTextNode("Item " + i));
    let (j = i) {
        item.onclick = function (ev) {
            console.log("Item " + j + " is clicked.");
        };
    }
    list.appendChild(item);
}

即時関数

ただの実行
(function() {
  console.log("hoge");
})();
ただの実行2(非推奨!!)
+function() {
  console.log("hoge");
}();
返り値をもらう場合
var result = (function (param1, param2) {
    return param1 + param2;
}(1, 2));
console.log(result); //3
オブジェクトリテラル
var counter = (function() {
    var count = 0;
    return {
        increment: function() { 
            count += 1;
            console.log(count);
        },
        decrement: function() { 
            count -= 1;
            console.log(count);
        }
    };
}());

counter.increment(); //1
counter.increment(); //2
counter.decrement(); //1
プロパティ
var hoge = {
  piyo: 123,
  fuga: 'あいうえお',
  hogera: [1,2,3],
  hogehoge: function() { return 1;}
};

console.log(hoge.piyo); //123
console.log(hoge.fuga); //あいうえお
console.log(hoge.hogera[2]); //3
console.log(hoge.hogehoge()); //1
ただの実行3
(function(arg){alert(arg);}('良い記事'));

for(var i=0,s='ありがとう'; i < s.length; i++)(function(s) { alert(s)})(s[i]); 

即時関数その2

var MYFUNC = function() {
  var count = 0;
  function public_start(){ private_reset; }
  function private_reset(){ count=0; }
  function public_increment(){ private_increment(); }
  function private_increment(){ count++; }
  function public_get_count(){ return count; }
  return {
      start: private_reset,
      increment: public_increment,
      get_count: public_get_count
  };
}

var module = MYFUNC();
module.start();
module.increment();
module.increment();
module.increment();
module.increment();
console.log(module.get_count()); //4
module.start();
console.log(module.get_count()); //0

F2キーを押すと別ウィンドウを開く

function keyDownFunc(e){
        var key_code = e.keyCode;
        // F2 = 113
        if (e.keyCode == "113") {
                window.open(location.href+"&debug=1");
        }
}
// window.attachEvent はIE用
if (window.attachEvent) {
        document.attachEvent("onkeydown" , keyDownFunc);
}

改行コードを<br>に置換

var str = "あい\r\nうえお";
str = str.replace(/\r\n/g,"<br>");
str = str.replace(/\r/g,"<br>");
str = str.replace(/\n/g,"<br>");
document.write(str);

window.openで表示されたページから元ページの値を取得

元ページ
<script>
function preview(inputname) {
    var w = 360;
    var h = 644;
    var l = (window.screen.width - w)/2;
    var t = (window.screen.height - h)/2;
    var url = 'preview.php?textareaname=' + inputname;
        var feature = 'resizable=yes, location=no, center=yes, status=no, width=' + w + ', height=' + h + ', top=' + t + ', left=' + l;
    var win = window.open(url, 'preview', feature);
}
</script>

<form name="frm1">
<textarea name="txt1">あああ</textarea>
<input type="button" onClick="preview('txt1');" value="プレビュー" />
</form>
preview.php(window.openで開かれるページ)
<script>
var val = window.opener.document.frm1.<?php echo $_GET["textareaname"];?>.value;
val = val.replace(/\r\n/g,"<br>");
val = val.replace(/\r/g,"<br>");
val = val.replace(/\n/g,"<br>");
document.write(val);
</script>

createElement

<span id="list"></span>

<script>
// <li>Item 1</li> を作var item = document.createElement("li");
item.appendChild(document.createTextNode("Item 1"));

// span#list 内に<li>タグを挿入
var list = document.getElementById("list");
list.appendChild(item);
</script>

try..catch

function check(num) {
  if(num!=1) { throw "error:not 1"; }
}
try {
  check(2);
} catch (e) {
  console.log(e.message);
}

URLをパース

try {
    location.href.split('&').forEach(function(pair){
        var splits = pair.split('=');
        var key    = splits.shift();
        var value  = splits.shift();
        if ( key == 'action' ) {
            throw value;
        }
    });
}
catch (value) {
    console.log(value)
}

IEのバージョン取得

IE11まで対応
var userAgent = window.navigator.userAgent.toLowerCase();
if( userAgent.match(/(msie|MSIE)/) || userAgent.match(/(T|t)rident/) ) {
    var isIE = true;
    var ieVersion = userAgent.match(/((msie|MSIE)\s|rv:)([\d\.]+)/)[3];
    ieVersion = parseInt(ieVersion);
} else {
    var isIE = false;
}
console.log(isIE);
console.log(ieVersion);

IEか判定

function isIE() {
        var ua = navigator.userAgent;
        if (ua.match(/(MSIE)/i) || ua.match(/(Trident)/i)) {
                return true;
        }
        return false;
}

チェックボックスのチェック全部ON/OFF

var chk1 = document.getElementsByTagName("chk1");
for(var i=0; i < chk1.length; i++){
  chk1[i].checked = true;
}

match

match_pattern
var str = 'see Chapter 3.4.5.1';
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);
console.log(found); //[ "Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1" ]

var str = 'see Chapter 3.4.5.1';
var re = /chapter \d+(\.\d)*/i;
var found = str.match(re);
console.log(found); //[ "Chapter 3.4.5.1", ".1" ]
g
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array);//[ "A", "B", "C", "D", "E", "a", "b", "c", "d", "e" ]

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/i;
var matches_array = str.match(regexp);
console.log(matches_array);//[A]

配列、連想配列

配列

配列の様々な書き方
var array = ['hoge', 'fuga'];
var array = new Array('hoge', 'fuga');
var array = Array('hoge', 'fuga');
var array = []; array[0] = 'hoge'; array[1] = 'fuga';
var array = []; array['0'] = 'hoge'; array['1'] = 'hoge'

var array = { 0: 'hoge', 1: 'fuga', length: 2 };
array.__proto__ = Array.prototype;
for
Array.prototype.hoge = function() {};

for (var i in ['a', 'b', 'c']) {
  alert(i); // 1, 2, 3, hoge が表示される
}

連想配列

連想配列の様々な書き方
var obj = { hoge: 'hoge' };
var obj = { 'hoge': 'hoge' };
var obj = {}; obj.hoge = 'hoge';
var obj = {}; obj['hoge'] = 'hoge';
var obj = new Object(); obj.hoge = 'hoge';
for..in
var hash = { hoge: 'hoge', fuga: 'fuga' }
for (var i in hash) {
  console.log(hash[i]);
}

cookieに書き込みができているか確認方法

document.cookie = "hoge=1; fuga=2; piyo=3;";
if(document.cookie.match(/fuga/)) {
    console.log("書き込み成功");
} else {
    console.log("書き込み失敗");
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1