Getting the ID of the element that fired an event
Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
<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>
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.
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);
});
});
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)'
, eg:
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
For reference, try this! It works!
jQuery("classNameofDiv").click(function() {
var contentPanelId = jQuery(this).attr("id");
alert(contentPanelId);
});
Though it is mentioned in other posts, I wanted to spell this out:
$(event.target).id
is undefined
$(event.target)[0].id
gives the id attribute.
event.target.id
also gives the id attribute.
this.id
gives the id attribute.
and
$(this).id
is undefined.
The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.
(It tripped me up, so it probably tripped up someone else)
链接地址: http://www.djcxy.com/p/14622.html上一篇: 如何使用JavaScript检查元素是否真的可见?
下一篇: 获取触发事件的元素的ID