jQueryでボタンが押された時にその近くにある要素に対して表示を操作する方法について考えていきたいと思います。
お題は以下のイメージ図にあるように、あいうえお等が書いてある要素に対して表示、非表示を考えていきます。12月6日記事
イメージ
要素の要素の指定をまとめると、
prev()1つ前の要素 next()1つ次の要素 children()すべて子要素 parent()すべての親要素 siblings()すべて兄弟の要素
となります。
HTML
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="reset.css"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(function() { $("button").click(function() { /*検証用 $(this).parent().prev().children().css('background','#000'); */ $(this).parent().prev().children().toggle('slow'); /*buttonに対してどの要素かを相対的に指定していく。 parent()親要素 prev()直前の要素 children()子要素 これらをつなげて指定していく。 */ }); }); </script> <title>jQueryで要素の移動</title> </head> <body> <article class="contents"> <div class="problem_container"> <p class="problem_contents">あいうえお </p> </div> <div class="answer"> <button class="btn">答え</button> </div> </article> <article class="contents"> <div class="problem_container"> <p class="problem_contents">かきくけこ </p> </div> <div class="answer"> <button class="btn">答え</button> </div> </article> <article class="contents"> <div class="problem_container"> <p class="problem_contents">さしすせそ </p> </div> <div class="answer"> <button class="btn">答え</button> </div> </article> </body> </html>
CSS
@charset "utf-8"; /* CSS Document */ .contents { width: 500px; height: 300px; background: #F2F2F2; margin-bottom: 10px; } .problem_container { float: left; width: 300px; height: 40px; background: #FFC; } .problem_contents { display:none; width: 280px; height: 30px; background: #CFF; } .answer { float: left; background: #FF0; width: 100px; height: 40px; } .btn { float: left; width: 50px; height: 30px; }
buttonの親要素(parent)はdiv.answerであり、その直前の要素(prev)はdiv.problem_containerであり、その子要素(children)はdiv.problem_contents
なのでそれらをつなげていき、最後に処理(今回の場合はtoggleメソッドを使った)を書いていけば思うように指定ができると思います。
以上