why event.target selects next element
I am having the following code. Here When i click one the a
tag i just like to get this element id
.but e.target
select next element can some one explain
$(document).ready(function(){
function doaction(e) {
var eve, id;
eve = $(e.target);
id = eve.attr('id');
alert(id);
}
$(".delete").click(function(e) {
doaction(e);
});
});
<div class="delete" id="del/one"><a href="javascript:void(0);" id="delete/1" >one</a></div>
<div class="delete" id="del/two"><a href="javascript:void(0);" id="delete/2">two</a></div>
<div class="delete" id="del/three"><a href="javascript:void(0);" id="delete/3" >three</a></div>
for demo
http://jsf开发者_运维问答iddle.net/gchoken/SGvUd/4/
Your jsFiddle link works fine. Just to explain, the click event is on the div
, not on the a
. So, if you click on the a
, you'll get that ID, but if you click inside the div
, but not on the a
, you'll get the div
ID, not the a
ID. Since the a
is inside the div
, clicking on that will trigger the event.
e.target
gives you the actual element that was clicked.
To get the element that you registered the handler for, use this
.
when you do this: $(".delete").click(function(e) {
you're getting the click event of the DIV with a class nammed "delete"
if you whant to get the click of A tag you must put the class "delete" on tha a tag and make the following code Example:
$("a.delete").click(function(){ //Code here })
It works ok for me. However, if you're having some problems, you may want to fix ID's in your code. The ID
attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters (A-Za-z), digits (0-9), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
try this one...
$(document).ready(function(){
function doaction(e) {
var eve, id;
eve = $(e.target.parentNode);
id = eve.attr('id');
alert(id );
}
$(".delete").click(function(e) {
doaction(e);
});
});
e.target gives you actual element which is being clicked, and div is parent of that element so..use e.target.parentNode
to get div id..
hope this helps..
Working Demo
精彩评论