I have a 3*3 table. When I click on td
element in my console log td
is printed six times and I want it to print out just once. Why is this happening and how to prevent it?
JS:
$("*").click(function(event){
console.log(event.target);//is this here executing 6 times, why...
});
HTML:
<table>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
This is happening because of propagation. Since you used
$('*')
it attached the click handler seperately to each element. Therefore, when you clicked ontd
, the event bubbled up to parent element handlers.To see the difference, try
or stop propagation