Setup:
I have written a jQuery function to update table cells of table_2, when a row in table_1 is clicked. Here is what I have written:
<script type="text/javascript">
$("tr").live('click',function() {
var host = $(this);
alert('A row in table 1 is clicked!');
var count = host.find("td").eq(2).text();
$("#myTable_2 tr:eq(0) td:eq(1)").text(count);
$("#myTable_2 tr:eq(1) td:eq(1)").text(5);
});
</script>
The Problem:
When I step-through this function using FireBug, I can see the cell data in myTable_2 is being changed. BUT, for every click, the function is executed twice. I can see the alert box appearing twice for each click.
Can somebody tell me why does this happen? And how to avoid this?
Either of the following:
To solve this, make your selector more specific. If you’re using jQuery 1.7+, use
.oninstead oflive: http://jsfiddle.net/6UmpY/3/Note: Using
.oninstead oflivedid not solve the problem.Using a more specific selector did fix the issue.
If you love
live, the following would also work: http://jsfiddle.net/6UmpY/4/