jQuery1.9の現象なのかわかりませんが、予め設定しておいたイベントが、後からjQuery.html()で追加した要素に効かないという現象がありました。
1.8ぐらいのときに、.click(function(){})でこのようなことが言われて、.liveを使おうだの.onだの.delegateだのとあって、.onで落ち着いたのかと思いましたが。
jQuery2とかだと解消しているんでしょうか。
同じようなこと(.on("click"))ばかり書いていてわかりにくいですが、下記のようなコードになります。
$(document).ready(function() {
// [1]
$("#def").on("click", function(){
alert("def");
});
// [2]
$("#appendalert").on("click", function() {
$("#appended").append(
$("<input />")
.attr("type","button")
.attr("id","appended")
.val("appended")
)
});
$("#appended").on("click", function() {
alert("appended");
});
// [3]
$("#createbutton").on("click", function() {
$("#createbuttonhtml").html(
'createbuttonhtml<input type="button" id="createdhtml" value="createdhtml" />'
);
});
$("#createdhtml").on("click", function() {
alert("createdhtml");
});
});
[1]id:defの要素に、直接オンクリックイベントを設定しておくと、もちろん実行されます。defボタンを押すと、「def」とアラートが出ます。
[2]「appendalert」というボタンを押すと、「appended」というid:appendedのボタンを .appendで 作ります。
ページ読み込み時に、id:appendedにオンクリックイベントを設定しておきます。
このとき作成されたid:appendedのボタンを押すと、オンクリックイベントが実行されます。
[3]「createbutton」というボタンを押すと、「createdhtml」というボタンを .htmlで 作ります。
ページ読み込み時に、id:createdhtmlにオンクリックイベントを設定しておきます。
このとき作成されたid:createdhtmlのボタンを押しても、オンクリックイベントが 実行されません 。。
悲しい。何のための.onなのか。
.htmlメソッドってこういうものなのでしょうか。
この問題で検索する時に、onもhtmlも一般語過ぎて引っかからない。
HTML全文はこちら。
<html>
<head>
<script src="./jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// [1]
$("#def").on("click", function(){
alert("def");
});
// [2]
$("#appendalert").on("click", function() {
$("#appended").append(
$("<input />")
.attr("type","button")
.attr("id","appended")
.val("appended")
)
});
$("#appended").on("click", function() {
alert("appended");
});
// [3]
$("#createbutton").on("click", function() {
$("#createbuttonhtml").html(
'createbuttonhtml<input type="button" id="createdhtml" value="createdhtml" />'
);
});
$("#createdhtml").on("click", function() {
alert("createdhtml");
});
});
</script>
</head>
<body>
[1]
<div>
<input type="button" id="def" value="def" />
</div>
<br />
[2]
<div>
<input type="button" id="appendalert" value="appendalert" />
</div>
<div id="appended">
appendalert
</div>
<br />
[3]
<div>
<input type="button" id="createbutton" value="createbutton" />
</div>
<div id="createbuttonhtml">
createbuttonhtml
</div>
</body>
</html>