The event.target
function works well for div and not for table element.
html code:
<div class="one body" >
sd
</div>
<div class="two body">
sddsd
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body">jjj</table>
js:
$(".body").click(function(e){
alert("xxxxxxxxx"+e.target.className);
});
DEMO: /
The event.target
function works well for div and not for table element.
html code:
<div class="one body" >
sd
</div>
<div class="two body">
sddsd
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body">jjj</table>
js:
$(".body").click(function(e){
alert("xxxxxxxxx"+e.target.className);
});
DEMO: http://jsfiddle/kavinhuh/z4rkW/31/
Share Improve this question edited Nov 14, 2013 at 15:28 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Nov 14, 2013 at 15:26 kavinhuhkavinhuh 7391 gold badge9 silver badges30 bronze badges 2-
1
Your HTML for your table is invalid. The
jjj
isn't actually rendered inside the table. You need (a<tbody>
and then) a<tr>
and finally a<td>
. – gen_Eric Commented Nov 14, 2013 at 15:31 - 1 Thank you all for your very helpful ments,I love stack overflow – kavinhuh Commented Nov 14, 2013 at 15:42
4 Answers
Reset to default 4Cause the actual e.target is a TD, not a table
Though you have an incorrect Table HTML Element structure. Tables are expected to have tr
and td
elements.
alert("Class: "+ event.target.className );
// is the Element that first fired the event ( TD
)
alert("Class: "+ this.className );
// is the element that was delegated to the event, in this case .body
This is because your HTML is illegal. If you have illegal HTML, you should not expect your code to work properly.
Text may not be a direct child of a table
. You need a tr
and either a td
or a th
. The browser reinterprets your HTML and makes something legal. In this case, it puts the text outside the table:
jjj
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="three body"></table>
This is taken from Chrome's DOM inspector. The solution is to put the text legally inside the table
.
Use this
instead of e.target
.
e.target
will give you the clicked element, not the element where the event has been attached to. When the element where the event has been attached to has child-elements this and you click on a child-element e.target
will return the child-element.
alert(this.className);
table
elements cannot have any text content so, your html will actually be rendered as
<div class="one body">
sd
</div>
<div class="two body">
sddsd
</div>
jjj<table class="three body" border="0" cellpadding="0" cellspacing="0" width="100%"></table>
Which is why your event handler is not firing when you click on jjj