I'm trying to write jquery-plugin for table.
我正在尝试为表编写jquery-plugin。
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
当我在第一个或第二个表上单击时,我总是得到相同的,最后一个对象id,它是:second_column,但不同的第一行或第二行id
click on [first column][tr id=f1][td class=name] output second_class f1
单击[第一列] [tr id = f1] [td class = name]输出second_class f1
click on [second column][tr id=s2][td class=select] output second_class s2
单击[第二列] [tr id = s2] [td class = select]输出second_class s2
and so on. Any ideas?
等等。有任何想法吗?
2 个解决方案
#1
Your line $this = $(this);
must be var $this = $(this);
.
你的行$ this = $(this);必须是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.
前者创建一个名为$ this的全局变量,并在每个循环的每次迭代中分配一个新值/引用 - 使用变量,因此始终指向最后一个迭代元素。后一个代码在循环体的闭包内创建一个变量 - 从而为每个单击处理程序提供对其行的引用。
#2
Try this
(function($) {
$.fn.smplPlugin = function() {
$("td",this).live('click', function() {
alert($(this).parent().attr('id') +" "+ $(this).parents('div').attr('id'));
});
};
})(jQuery);
#1
Your line $this = $(this);
must be var $this = $(this);
.
你的行$ this = $(this);必须是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.
前者创建一个名为$ this的全局变量,并在每个循环的每次迭代中分配一个新值/引用 - 使用变量,因此始终指向最后一个迭代元素。后一个代码在循环体的闭包内创建一个变量 - 从而为每个单击处理程序提供对其行的引用。
#2
Try this
(function($) {
$.fn.smplPlugin = function() {
$("td",this).live('click', function() {
alert($(this).parent().attr('id') +" "+ $(this).parents('div').attr('id'));
});
};
})(jQuery);