我有一个插件,它本质上是在服务器端对表进行排序并将内容放回到容器中。我有一个绑定(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/