設定されているイベント処理を取り消すには
off()命令を使います。
$( セレクター ).off( "イベント発生の条件" );
サンプルコードでは、a要素がクリックされるとimg要素を
書き換える処理が設定されています。「a要素取消」ボタンを
クリックすると、off()でa要素のイベントを消します。
取り消すと画像を切り替える機能がなくなるので
通常のリンクになります。
実行結果はこちらです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>jQueryStudy</title> <style> *{margin:0;padding:0;} #container{ width:640px; height:400px; background-color:white; font-weight:100; margin:0 auto;} #box{ width:100px; height:100px; background-color:blue;} button,li{margin:8px;} </style> <script src="js/jquery-1.11.3.js"></script> </head> <body> <div id="container"> <button>a要素取消</button> <ul> <li><a href="kuroneko.jpg">黒猫</a></li> <li><a href="shironeko.jpg">白猫</a></li> <li><a href="mikeneko.jpg">三毛猫</a></li> </ul> <p><img src="kuroneko.jpg" alt="黒猫" width="100" height="100"></p> </div><!--contatiner--> <script> $(document).ready(function(){ $("a").click(function(){ $("img").attr("src",$(this).attr("href")) .attr("alt",$(this).text()); return false; }); $("button").click(function(){ $("a").off("click"); }); }); </script> </body> </html> |