jQueryではまる
jQueryの実装ではまっている。
index.html
<!DOCTYPE html> <html> <head> <title>test</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script src="script.js"></script> </head> <body> <div id="main"></div> </body> </html>
script.js
$(function () { setInterval(function () { $("#main").prepend('<p class="test">hago</p>'); $(".test").on('click',function () { $(".test").off('click'); alert(1); }); }, 1000) });
1秒ごとにpタグを追加して表示するスクリプト。pタグにはclickイベントを付けて、クリックしたらアラートさせたい。アラートを一度は良い。
しかし、このコードだと、pタグをクリックした際、複数回アラートする場合がある。setintervalで、繰り返しpタグにclickイベントが付与されている影響かなと。
てことで、解決方法を探そう。
--追記--
最近まで勤めていた会社の上司に教えてもらった。
script.js
$(function () { var i = 1; setInterval(function () { var test = 'test' + i; $("#main").prepend('<p id="'+ test +'">hago</p>'); $("#"+test+"").on('click',function () { alert(1); }); i++; }, 1000) });
pタグにユニークなidを付けて解決。
あざす!