Last active
November 18, 2019 07:40
-
-
Save yano3nora/7791cc7059fbf44d13838cd41285e7c3 to your computer and use it in GitHub Desktop.
[jquery: event note] handling of events on jquery. #jquery #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery が内部に登録しているイベントを取得 / 割込み | |
* @see https://qiita.com/dz_/items/e5da8ed692720a69126c | |
*/ | |
// クリックイベントに設定されたハンドラを取得する | |
var events = $._data($('#submit').get(0), 'events'); | |
// ハンドラの全削除 | |
$._data($('#submit').get(0)).events = []; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//以下のように要素を選択してから on イベントで発火タイミングを設定していても、動的に追加されたDOMはこれでとらえられない。 | |
$("#element").on("click", (function(){ | |
alert("要素をクリックしました"); | |
}); | |
//ドキュメント自体にイベントリスナを設定して on イベントハンドラの第二引数に要素を指定すると検知できる。 | |
$(document).on("click", "#addedElement", (function(){ | |
alert("動的に追加された要素をクリックしました"); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// attr() だと古い書き方 'el.change()' みたいな感じで動的追加DOMに対処できない | |
// 以下全選択チェックみたいなやつがチェックされたら全部チェック・チェック外すみたいなサンプル | |
$(document).on('change', '#all-check', function(){ | |
var $checkboxes = $('.checkbox'); | |
if($(this).is(':checked')) { | |
$checkboxes.prop('checked', true); | |
} else { | |
$checkboxes.prop('checked', false); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dispatchEventのラッパってことで理解いいのかしら... | |
// changeイベントの強制発火でchangeイベントリスナに知らせる | |
$('#hoge').find('input[type="text"]').val('changedValue').trigger('change', [arg1, arg2]); | |
// 第2引数の配列は可変長でイベントリスナのコールバックに渡せる | |
$('#hoge').find('input[type="text"]').on('change', function (event, arg1, arg2) {}); | |
// jQueryUIのDatepickerとかはonselectのコールバックに実装する。 | |
$(".js-datePicker").datepicker({ | |
showOn: "both", | |
onSelect: function(dateText, inst) { | |
$(this).val(dateText); | |
$(this).trigger('change'); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment