【问题标题】:jQuery: There's a more efficient way of doing this, isn't there?jQuery:有一种更有效的方法来做到这一点,不是吗?
【发布时间】:2011-04-26 03:09:52
【问题描述】:

我有一个插件,它本质上是在服务器端对表进行排序并将内容放回容器中。我有一个绑定函数,它向表头单元格添加一个点击事件来调用父表单提交。我觉得这不是解决这个问题的最佳方式。有什么想法吗?

$.fn.myplugin = function() {
  return this.each(function() {
    var parentform = $(this).parents("form");
    var tableidentifier = $(this).attr("id");

    var bindclicks = function() {
      parentform.find("table#" + tableidentifier + " thead tr th").click(function() {
        // Some code to change the sort column- boring!
        parentform.submit();
      });
    }

    bindclicks();

    parentform.submit(function() {
      $.post(parentform.attr("action"), parentform.serialize(), function(res) {
        parentform.find("table#" + tableidentifier).replaceWith($(res));
        bindclicks();
      })
      return false;
    });
  });
}

我首先调用bindclicks() 函数来设置点击处理程序,然后因为我在做replaceWith() 我再次调用它来重新绑定这些事件。它有效,但我很好奇..

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以使用.delegate(),这样您就不需要每次都重新绑定您的点击处理程序。

    $.fn.myplugin = function() {
        return this.each(function() {
            var parentform = $(this).parents("form");
            var tableidentifier = $(this).attr("id");
    
            parentform.delegate("table#" + tableidentifier + " thead tr th", "click", function() {
                parentform.submit();
            });
    
            parentform.submit(function() {
                $.post(parentform.attr("action"), parentform.serialize(), function(res) {
                    parentform.find("table#" + tableidentifier).replaceWith($(res));
                })
                return false;
            });
        });
    }
    

    只显示 snip-it,这应该可以工作,因为您要替换 <table/> 并且委托事件绑定到 <form/>

    【讨论】:

    • 酷!从未使用过delegate 函数——非常非常方便。
    【解决方案2】:

    而不是这个:

        var bindclicks = function() {
            parentform.find("table#" + tableidentifier + " thead tr th").click(function() {
                parentform.submit();
            });
        }
    
        bindclicks();
    

    试试这个:

    $("table#" + tableidentifier + " thead tr th", parentForm)
        .bind('click', function() {
            parentForm.submit();
        });
    

    如果您使用live 而不是bind,它会将点击处理程序绑定到任何新创建的元素。

    【讨论】:

    • 表单提交后我不需要在$.post回调中发布相同的代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多