備忘録 @ ウィキ
JavaScript
最終更新:
mlnk
-
view
Tips
フォーカスされているエレメントを取得する
var element = (document.activeElement || window.getSelection().focusNode);
前半がIE/Opera用。getSelectionはFirefox用。
文字列の置換
var str = '10-10-10';
ret = str.replace(/-/, ':'); // 10:10-10 : 最初のマッチしか置換されない
ret = str.replace(/-/g, ':'); // 10:10:10 : OK
型の取得
if(typeof e=='string')
alert('string');
JSON を eval
var json = "{'a':'b'}";
var o = eval(json); // invalid labelで失敗する
var o = eval('('+json+')'); // ok
イベントハンドラの追加
function observe(target, type, listener) {
if (target.addEventListener)
target.addEventListener(type, listener, false);
else if (target.attachEvent)
target.attachEvent('on' + type, function() { listener.call(target, window.event); });
else
target['on' + type] = function(e) { listener.call(target, e || window.event); };
}
// こっちの方がいいと思う
var observe = window.addEventListener ?
function(target, type, listener) {
target.addEventListener(type, listener, false);
}
:
function(target, type, listener) {
target.attachEvent('on' + type, function(){listener.call(target, window.event);});
};
offsetWidth と clientWidth の違い
offsetWidth は内容の幅+枠線の幅
clientWidth は内容の幅のみ
数値と文字列の相互変換
-
文字列->数値
n = "123"-0; n = Number("123"); n = parseFloat("123"); n = parseInt("123"); n = eval("123");
-
数値->文字列
s = 123+""; s = String(123);