jQueryでコミュニティ参加脱退処理の実装をしています。
参加ボタン押下時は脱退ボタンに切り替わり、
脱退ボタン押下時はモーダルを表示し、「脱退します」を選択すると参加ボタンに切り替わります。
withdrawクラスを付けたり外したりするとボタンの色が変わります。
その要件を以下のように実装しました。
動きとしては想い通りに動いているのですが、懸念点が2点あります。
質問の内容としては、次の2つの懸念点を解消するにはどのように実装すればいいでしょうか?
懸念点は以下
1.「$('.box1').on('click','.box2',function(){...」を参加の時も脱退の時も実行してしまう。
→参加ボタンを押した時だけにしたい
2.onが複数登録されてしまう気がする。
→複数登録されないようにしたい
この2点を解消したいです。もしアドバイスが頂ける方がいればよろしくお願い致します。
html
1<!DOCTYPE html> 2<html> 3<head> 4<meta charset="UTF-8"> 5<title>Insert title here</title> 6<style type="text/css"> 7<!-- 8.box2 { 9background: skyblue; 10width:300px; 11height:250px; 12margin:20px; 13} 14.withdraw { 15background: red; 16width:300px; 17height:250px; 18margin:20px; 19} 20--> 21</style> 22<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 23<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> 24<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> 25</head> 26<body> 27<div class="box1"> 28 <div class="box2">参加</div> 29</div> 30<br> 31<div id="modal" title="Basic dialog"> 32 <p>コミュニティから脱退しますか?</p> 33</div> 34</body> 35<script type="text/javascript"> 36$(function(){ 37 $('.box1').on('click','.box2',function(){ 38 $(this).addClass("withdraw").text("脱退"); 39 }); 40 41 // モーダル初期設定 42 $('#modal').dialog({ 43 autoOpen: false, // 自動でオープンしない 44 modal: true, // モーダル表示する 45 resizable: false, // リサイズしない 46 draggable: false, // ドラッグしない 47 show: "clip", // 表示時のエフェクト 48 hide: "fade", // 非表示時のエフェクト 49 buttons: { 50 "脱退します": function() { 51 $(this).dialog( "close" ); 52 $('.box1').children().removeClass("withdraw").text("参加"); 53 }, 54 Cancel: function() { 55 $( this ).dialog( "close" ); 56 } 57 } 58 }); 59 60 // .withdraw クリック時にモーダル表示 61 $('.box1').on('click','.withdraw',function () { 62 $('#modal').dialog('open'); 63 return false; 64 }); 65 66 // モーダル画面以外のブラウザ領域をクリックで、モーダル非表示 67 $(document).on('click', '.ui-widget-overlay', function(){ 68 $(this).prev().find('.ui-dialog-content').dialog('close'); 69 }); 70}); 71 72</script> 73</html>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。