开发者

jQuery: There's a more efficient way of doing this, isn't there?

开发者 https://www.devze.com 2023-02-28 09:53 出处:网络
I have a plugin which essentially sorts a table on the server side and puts the content back into a container. I have a binding function which adds a click event to the table header cells to call the

I have a plugin which essentially sorts a table on the server side and puts the content back into a container. I have a binding function which adds a click event to the table header cells to call the parent form submission. I feel like this isn't the best way of going about this. Any ideas?

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

I call the bindclicks() function first to set the click handlers up, then since I am doi开发者_运维技巧ng replaceWith() I am calling it again to re-bind those events. It works, but I'm curious..


You could use .delegate() so you do not need to rebind your click handler each time.

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

With just the snip-it shown, this should work since you are replacing the <table/> and the delegated event is bound to the <form/>


Instead of this:

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

    bindclicks();

Try this:

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

If you use live instead of bind, it'll bind the click handler to any newly created elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号