获取触发事件的元素的 ID [英] Getting the ID of the element that fired an event
问题描述
有没有办法获取触发事件的元素的 ID?
Is there any way to get the ID of the element that fires an event?
我在想:
$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});
<script type="text/javascript" src="starterkit/jquery.js"></script>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
当然,var test
应该包含 id "aaa"
,如果事件是从第一个表单触发的,并且 "bbb"
,如果事件是从第二种形式触发的.
Except of course that the var test
should contain the id "aaa"
, if the event is fired from the first form, and "bbb"
, if the event is fired from the second form.
推荐答案
在 jQuery 中 event.target
总是指触发事件的元素,其中 event
是传递给函数的参数.http://api.jquery.com/category/events/event-object/一个>
In jQuery event.target
always refers to the element that triggered the event, where event
is the parameter passed to the function. http://api.jquery.com/category/events/event-object/
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
还要注意 this
也可以工作,但它不是一个 jQuery 对象,所以如果你想在它上面使用一个 jQuery 函数,那么你必须把它称为 $(这)
,例如:
Note also that this
will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this)
, e.g.:
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
这篇关于获取触发事件的元素的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!