jQueryにてイベント内のセレクタで自身の要素を選択するコードを紹介します。
概要
jQueryのイベント内で自身の要素をセレクタで選択する場合は
$(this)
または
jQuery(this)
と記述します。
コード
以下のコードを記述します。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="jquery-2.0.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".squareButton").click(function () {
$(this).css("background-color","#A0C0FF");
})
})
</script>
<style type="text/css">
.squareButton {
width: 64px;
height: 64px;
margin-left: 8px;
margin-right: 8px;
border: 1px dashed #404040;
float: left;
}
</style>
</head>
<body>
<div class="squareButton"></div>
<div class="squareButton"></div>
<div class="squareButton"></div>
<div class="squareButton"></div>
<div class="squareButton"></div>
</body>
</html>
解説
<script type="text/javascript">
$(document).ready(function () {
$(".squareButton").click(function () {
$(this).css("background-color","#A0C0FF");
})
})
</script>
$(document).ready(function () {
...
}
上記のコードにより、ページ表示後にJavaScriptが実行されます。
$(".squareButton").click(function () {
$(this).css("background-color","#A0C0FF");
})
"squareButton"クラスの要素のクリックイベントを実装します。クリックイベントでは$(this)セレクタを用いクリックされた要素のみ、背景色を変更します。
実行結果
上記のHTMLファイルを表示すると下図の画面が表示されます。
枠をクリックするとクリックした枠の背景色が変わります。
クリックされた枠のみセレクタで選択できています。
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2014-01-09