Last active
June 13, 2022 03:23
-
-
Save kobitoDevelopment/6d8c8f0c5a8eafa46787b09e5dfb6f6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<p class="hoge1">テスト1</p> | |
<p class="hoge2">テスト2</p> | |
<p class="hoge3">テスト3</p> |
This file contains hidden or 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
/* | |
第一引数:存在をチェックしたいイベントor関数実行のトリガー要素 | |
第二引数:イベントタイプ(関数を実行する場合は"function") | |
第三引数:実行したい関数名 | |
*/ | |
function searchRunner(target, handle, callback) { | |
if (document.querySelector(target) != null) { | |
let targetElement = getElements(target); | |
targetElement.forEach(function (elem, index) { | |
if (handle === "function") { | |
callback("テスト4"); | |
} else { | |
elem.addEventListener(handle, callback); | |
} | |
}); | |
} | |
} | |
/* 要素を取得する */ | |
function getElements(elem) { | |
let targetElement = document.querySelectorAll(elem); | |
targetElement = [...targetElement]; | |
return targetElement; | |
} | |
/* サンプル1 イベントのコールバックとして実行したい関数の処理を記述*/ | |
function callback1(event) { | |
// 挙動サンプル | |
event.target.style.color = "red"; | |
} | |
/* サンプル1 存在チェック+イベント発火を実行 */ | |
searchRunner(".hoge1", "click", callback1); | |
/* サンプル2 実行したい関数の処理を記述*/ | |
function callback2(sample) { | |
// 挙動サンプル | |
const hoge3 = document.querySelector(".hoge3"); | |
hoge3.textContent = sample; | |
} | |
/* サンプル2 存在チェック+関数発火を実行 */ | |
searchRunner(".hoge2", "function", callback2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment