LoginSignup
4
5

JavaScript / jQueryメモ

Last updated at Posted at 2018-02-18

備忘用。

JavaScript

textareaは ×textContent ○value

See the Pen Untitled by fujisystem (@fujisystem) on CodePen.

Named capturing group

See the Pen Named capturing group by fujisystem (@fujisystem) on CodePen.

Non-capturing group

See the Pen Non-capturing group by fujisystem (@fujisystem) on CodePen.

Jsのメソッド解析

# ECMAScript® 2022 Language Specification
https://tc39.es/ecma262/multipage/global-object.html

JsでEnumぽいの

ES6
const Suits = {
  HEART: Symbol('heart'),
  DIAMOND: Symbol('diamond'),
  SPADE: Symbol('spade'),
  CLUB: Symbol('club'),
  exsitsByKey: x => Object.keys(Suits).includes(x.toUpperCase()),
  exsits: x => Object.values(Suits).includes(x),
  getByCode: x => Object.entries(Suits).filter(([k, v]) => k === x.toUpperCase()).map(([k, v]) => v).find(v => v),
};

// Enums.
let dia = Suits.DIAMOND;
console.log( Suits.exsitsByKey(dia.description) ); // => true
console.log( Suits.exsits(dia) ); // => true
console.log( Suits.getByCode('diamond')?.description ); // => "diamond"
console.log( dia === Suits.getByCode('diamond') ); // => true

3桁カンマ付与

引数は数値型
const addCommas = n => new Intl.NumberFormat().format(n);

オプショナルチェーン演算子/Null合体演算子

const hogeJoho = [{'testCode':10}, {'testCode':20}];
const found = hogeJoho?.find(e => e.testCode === 10);
setData(found?.testCode ?? 'defaultValue');

querySelectorを$にする

$=document.querySelector.bind(document);
または
const $=e=>document.querySelector(e);

2次元配列をfalseで初期化

const getTwoDimensionalArray = w => h => [...Array(h)].map(() => Array(w).fill(false));

複数配列を初期化

var ary = Array.apply( null, Array(3) ).map( function(){ return 0 } );
console.log( ary );  // Array(3) [ 0, 0, 0 ] と表示

文字列から文字の配列を作成

var a3 = Array.from('Japan');
console.log(a3);  // [ 'J', 'a', 'p', 'a', 'n' ] と表示

(初心者向け) JavaScript 配列の作成と初期化から拝借。

自動更新(オートリロード)のブックマークレット

javascript:(function(){var T=prompt('更新間隔?(秒)','60');if(T&&!isNaN(T)){var F='<html><frameset rows="*,0"><frame src="'+location+'"><frame></frameset></html>';var W=open();with(W.document){write(F);close();}var H='<html><script>function R(){parent.frames[0].location="'+location+'";}setInterval("R()",'+T*1000+');</script></html>';with(W.frames[1].document){write(H);close();}}})();

Bookmarklet for ”Reload Every”
から拝借。

8桁のランダムな[0-9a-z]な文字列取得

Math.random().toString(36).slice(-8)

36進数(10文字+26文字)で0-9a-zな文字列を取得するらしい。

N桁の数字文字列取得(zero-padding)

function getZeroPadding( number, digits ){
  return ( Array( digits +1 ).join('0') + number ).slice( -digits );
}

String.prototype.padStart()なるものが「ECMAScript 2017 (ECMA-262)」からあるらしい。※IE以外。Edgeはいける。

console.log( '1'.padStart(2, "0") );

ファイルパスからファイル名取得 (Windows限定)

var isWindows = navigator.userAgent.match(/Win(dows )?NT /);
var fileSeparator = isWindows ? '\\' : '/';
function getFilename( path ) {
  return isWindows ? path.split( fileSeparator ).pop();
}

配列の最大値取得

Math.max.apply(null, [-100, 0, 3.14, 0xFF, 1000]);

IE11 印刷プレビュー

function printPreviewIE11(){
  if(document.body.insertAdjacentHTML == null) return;
  var sWebBrowserCode = '<object width="0" height="0" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
  document.body.insertAdjacentHTML('beforeEnd', sWebBrowserCode);
  var objWebBrowser = document.body.lastChild;
  if(objWebBrowser == null) return;
  objWebBrowser.ExecWB(7, 1);
  document.body.removeChild(objWebBrowser);
}

ブラウザ判別(ブラウザ名取得)

function browser_name() {
  var userAgent = window.navigator.userAgent.toLowerCase();
  var appVersion = window.navigator.appVersion.toLowerCase();

  if (userAgent.indexOf("msie") > -1) {
    if (appVersion.indexOf("msie 6.0") > -1) {
      return "IE6";
    }
    else if (appVersion.indexOf("msie 7.0") > -1) {
      return "IE7";
    }
    else if (appVersion.indexOf("msie 8.0") > -1) {
      return "IE8";
    }
    else if (appVersion.indexOf("msie 9.0") > -1) {
      return "IE9";
    }
    else if (appVersion.indexOf("msie 10.0") > -1) {
      return "IE10";
    }
    else {
      return "Unknown";
    }
  }
  else if (userAgent.indexOf("trident/7.0") > -1) {
    return "IE11";
  }
  else if (userAgent.indexOf("edge") > -1) {
    return "Edge";
  }
  else if (userAgent.indexOf("firefox") > -1) {
    return "Firefox";
  }
  else if (userAgent.indexOf("opera") > -1) {
    return "Opera";
  }
  else if (userAgent.indexOf("chrome") > -1) {
    return "Google Chrome";
  }
  else if (userAgent.indexOf("safari") > -1) {
    return "Safari";
  }
  else {
    return "Unknown";
  }
}

jQuery

テーブルの見出し以外削除(初期化)

$("#table tr:gt(0)").remove();

セレクトボックス選択値取得

var hoge = $("#select option:selected").val();

セレクトボックス初期化

$("#select").val(0);
または
$("#select").children().remove();

チェックボックス判定

if ( $("#check").prop('checked') ){
}

DOMツリー構築が完了と同時に実行(≒body onLoad)

$(function(){
});

配列の存在確認

if ( $.inArray("hoge", ["hoge", "foo"] ) !== -1 ){
}

ローカル実行時のファイルダウンロード

var text = "テストテキスト";
var blob = new Blob([text], {type: "text/plain"});  // バイナリデータ作成

// IEか他ブラウザかの判定
if(window.navigator.msSaveBlob)
{
    // IEなら独自関数
    window.navigator.msSaveBlob(blob, "ファイル名.txt");
} else {
    // それ以外はaタグ利用
    var a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.target = '_blank';
    a.download = 'ファイル名.txt';
    a.click();
    document.body.removeChild(a);
}

toolバーのarea固定

$(window).on('load',function(){
  if($("#tools").length > 0){
    var tool = $("#tools");
    var area = $(".main-text");
    var offset = tool.offset();
    var myLeft = offset.left;
    var myTop = offset.top;
    $(window).scroll(function(){
      // 高さ取得
      var toolBottom = tool.height() + $(this).scrollTop();
      var areaBottom = area.offset().top + area.height();
      if($(window).scrollTop() > myTop) {
        if(areaBottom < toolBottom){ // 指定エリアより下
          tool.css({
            "position":"absolute",
            "top":"auto",
            "bottom":"0",
            "right":"0"
          });
        } else { // 指定エリア内は固定
          tool.css({
            "position":"fixed",
            "top":"0",
            "bottom":"auto",
            "right":"auto",
            "margin-left":"645px" // 756-48-63
          });
        }
      } else { // 指定エリアより上
        tool.css({
          "position":"absolute",
          "top":"0",
          "bottom":"auto",
          "right":"0"
        });
      }
    });
  }
});
4
5
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
4
5