Reputation: 97
I'm trying to write jquery-plugin for table.
I have 2 dynamic tables from server:
(function($) {
$.fn.smplPlugin = function() {
return this.each(function() {
$this = $(this);
$this.find("td").live('click', function() {
alert($this.attr('id') +" "+ $(this).parent().attr('id'));
});
});
};
$(document).ready(function() {
$("#first_column").smplPlugin ();
$("#second_column").smplPlugin ();
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="first_column">
<table>
<tr id="f1">
<td class="select">some text</td>
<td class="name">some name</td>
</tr>
<tr id="f2">
<!--
....
more same rows
....
-->
</tr>
</table>
</div>
<div id="second_column">
<table>
<tr id="s1">
<td class="select">some text</td>
<td class="name">some name</td>
</tr>
<tr id="s2">
<!--
....
more same rows with differents id's
....
-->
</tr>
</table>
</div>
then I want to add click event on <td>
.
when I click on <td>
on first or on second table, I always get the same, last object id, it's: second_column, but different first or second rows id's
click on [first column][tr id=f1][td class=name] output second_class f1
click on [second column][tr id=s2][td class=select] output second_class s2
and so on. Any ideas?
Upvotes: 0
Views: 2250
Reputation: 3333
Your line $this = $(this);
must be var $this = $(this);
.
The former creates a global variable called $this
and assigns a new value/reference in each iteration of your each-loop – using the variable thus always points to the last iterated element. The latter code creates a variable within the closure of your loop body – thus giving each click-handler a reference to its row.
Upvotes: 1
Reputation: 10676
Try this
(function($) {
$.fn.smplPlugin = function() {
$("td",this).live('click', function() {
alert($(this).parent().attr('id') +" "+ $(this).parents('div').attr('id'));
});
};
})(jQuery);
Upvotes: 0