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メソッドを使った)を書いていけば思うように指定ができると思います。

以上

最終更新:2015年12月06日 12:33
添付ファイル