2
2

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.

HTMLイベント要素を画面遷移に伴って変更する時に留意すること

Last updated at Posted at 2012-04-11

僕はJavaScriptで開発を行うときにjQueryを使っています。
書き方が好きだからです。それをともかく、画面遷移などに伴いHTMLの要素を変更する場合があります。ボタンを表したり、文字を変えたり。イベント駆動するようになっている要素を変更する場合もあるでしょう。例えば以下のボタンクリックの場合、BeforeがAfterButtonとなります。

main.html
<input id="someButton" type="button"/>

<div id="someText">Before</div>

event.js
$(function(){
	$("#someButton").click(clicked);
	$("#afterButton").click(afterClicked);
});

function clicked(){
    /*ボタンクリックで起きる動作*/
	$("#someText").html("<input id='afterButton' type='button' value='AfterButton'/>");
}

function afterClicked(){
	alert("I am AfterButton");
}

someButtonを押しますとAfterButtonが出現します。じつはここでAfterButtonと押してもAfterButtonとは表示されませんでした。恐らく$();内で設定されたコールバックはHTMLロード時に一度呼ばれるだけで、その時に存在しなかったAfterButtonにはコールバックが設定されなかったのだと思います。コールバックはあくまでも設定されるときに存在している要素だけが得られるのですね。
そのためこの場合はもう一度

event.js
function clicked(){
    /*ボタンクリックで起きる動作*/
	$("#someText").html("<input id='afterButton' type='button' value='AfterButton'/>");
	$("#afterButton").click(afterClicked);
}

と設定する必要があります。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?