【问题标题】:jQuery dynamic table live click pluginjQuery动态表格实时点击插件
【发布时间】:2009-06-11 19:57:13
【问题描述】:

我正在尝试为表编写 jquery-plugin。

我有 2 个来自服务器的动态表:

(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>

然后我想在&lt;td&gt;上添加点击事件。

当我在第一个或第二个表上单击&lt;td&gt; 时,我总是得到相同的最后一个对象 id,它是:second_column,但第一行或第二行 id 不同

点击[第一列][tr id=f1][td class=name] 输出 second_class f1

点击[第二列][tr id=s2][td class=select]输出second_class s2

等等。 有什么想法吗?

【问题讨论】:

标签: javascript jquery jquery-plugins html-table


【解决方案1】:

您的线路$this = $(this); 必须是var $this = $(this);

前者创建一个名为$this 的全局变量,并在每个循环的每次迭代中分配一个新值/引用——因此使用该变量始终指向最后一个迭代元素。后面的代码在循环体的闭包中创建了一个变量——从而为每个点击处理程序提供了对其行的引用。

【讨论】:

    【解决方案2】:

    试试这个

    (function($) {
       $.fn.smplPlugin = function() {
        $("td",this).live('click', function() {
          alert($(this).parent().attr('id') +" "+ $(this).parents('div').attr('id'));          
         });
      };
    })(jQuery);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2021-01-16
      • 1970-01-01
      • 2016-05-03
      • 2020-05-30
      相关资源
      最近更新 更多