javascript - jQuery:有一种更有效的方法可以做到这一点,不是吗?

标签 javascript jquery

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

$.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() 我再次调用它来重新绑定(bind)这些事件。它有效,但我很好奇..

最佳答案

您可以使用 .delegate() 因此您不需要每次都重新绑定(bind)您的点击处理程序。

$.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;
        });
    });
}

仅显示片段,这应该可以工作,因为您正在替换 <table/>并且委托(delegate)事件绑定(bind)到 <form/>

关于javascript - jQuery:有一种更有效的方法可以做到这一点,不是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5781982/

相关文章:

javascript - 判断浏览器是否为IE最简单、最好的方法是什么?

javascript - 使用颜色选择器手动更改单元格/行/列的颜色?

javascript - 仅使用文本和数字将 div 中的文本包裹起来

javascript - 是否可以在另一个请求中有一个 Angular js $http 请求?

javascript - 数据验证php/mysql/jquery

javascript - 网络音频 API 无法在本地 Chrome 中工作

javascript - 在更改事件中将文本附加到 Summernote 元素时出现问题

javascript - js 无法在 bs3 ajax 模式中工作

javascript - 如何在javascript中格式化数据库日期时间?

javascript - 如何在 native react 中提取图像中最常用的颜色?