イベントを発生させた要素のIDを取得する方法はありませんか?
というようなことを考えています。
<html>
<head>
<script type="text/javascript" src="starterkit/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var test = caller.id;
alert(test.val());
});
});
</script>
</head>
<body>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
</body>
</html>
もちろん、var test
には、最初のフォームからイベントが発生した場合には "aaa"
を、2番目のフォームからイベントが発生した場合には "bbb"
を格納する必要がありますが。
jQueryでは、event.target
は常にイベントを起こした要素を指し、event
は関数に渡されるパラメータです。http://api.jquery.com/category/events/event-object/。
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
また、this
も動作しますが、これは jQuery オブジェクトではないので、jQuery 関数を使用したい場合は、$(this)
として参照する必要があります。
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
関数を実行したオブジェクトを参照するには,(this)
を使用します。
this'`は、click、each、bindなどのメソッドから呼び出されるコールバック関数の内部にいる場合(jQueryの文脈で)、 DOM 要素となります。
詳しくはこちらをご覧ください: http://remysharp.com/2007/04/12/jquerys-this-demystified/