LoginSignup
22
23

More than 5 years have passed since last update.

HTMLページ生成時のonclickより前に実行する関数を差し込む

Last updated at Posted at 2014-04-03

Webアプリを作る際にサーバサイドでアプリケーションフレームワークなどを使っている場合、
生成されたHTMLのonclick属性にすでに関数がセットされている場合があります。(wicketとかwicketとか…)

jQueryを使って、設定されているクリックイベントよりも前に
任意の関数を差し込みます。

prependEvent
prependEvent = function(target, newEvent) {
  var clickHandler;
  clickHandler = target[0].onclick; // イベントを退避
  target[0].onclick = null; // クリックイベントをリセット
  target.click(newEvent); // 差し込み
  target.click(clickHandler); // その後にオリジナルをしまう
};

↓こんなカンジで使います。

HTML
<input id="confirmButton" type="button" onclick="alert('first');" value="test input"/>
JavaScript
secondFunction = function() {
  alert("second");
};

prependEvent($("input#confirmButton"), secondFunction);

second -> first の順でアラートが出現します。

22
23
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
22
23