8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQuery の trigger の第2引数が便利だ

Last updated at Posted at 2018-02-09

jQuery の trigger の第2引数が便利だ

知らなかったのでメモ

jQuery('#id').on('change', changeAction);
function changeAction(event, argument1, argument2, argument3) {
    console.log('argument1: ' + argument1);
    console.log('argument2: ' + argument2);
    console.log('argument3: ' + argument3);
}
jQuery('#id').trigger('change', ['hoge', 'fuga', 'foo']);

って書くと、

jQuery('#id') の value値変更時は、

argument1: undefined
argument2: undefined
argument3: undefined

trigger 実行時は、

argument1: hoge
argument2: fuga
argument3: foo

ってコンソールに出力されます。

jQuery(document).ready 時のみ、実行させたくない処理がある時とか、
function の外に変数とか用意せずに↓な感じでかけるので便利。

jQuery(function(){
    jQuery('#id').on('change', changeAction).trigger('change', [true]);
    function changeAction(event, readyFlg) {
        // ここに共通処理

        if (readyFlg !== true) {
            // ここの処理は、jQuery(document).ready時には実行しない
        }
    }
});
8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?