how to reuse jQuery code in different selectors?

I write code like this below,the differences between is selectors,so how to reuse the similar method in less code? how about using a factory function?

$(".tc_banzhu").click(function() {
  $(".banzhuDon").fadeIn(200);
  //get the width and height of the dialog
  var tc_hgt = $(".banzhuDon .popup_box").height() / 2;
  var tc_wid = $(".banzhuDon .popup_box").width() / 2;
  $(".banzhuDon.popup_box").css({
    marginLeft: tc_wid * -1 + "px",
    marginTop: tc_hgt * -1 + "px"
  });
});
$(".tc_ban").click(function() {
  $(".banDon").fadeIn(200);
  var tc_hgt = $(".banDon .popup_box").height() / 2;
  var tc_wid = $(".banDon .popup_box").width() / 2;
  $(".banDon.popup_box").css({
    marginLeft: tc_wid * -1 + "px",
    marginTop: tc_hgt * -1 + "px"
  });
});
$(".tc_banner").click(function() {
  $(".bannerDon").fadeIn(200);
  var tc_hgt = $(".bannerDon .popup_box").height() / 2;
  var tc_wid = $(".bannerDon .popup_box").width() / 2;
  $(".bannerDon.popup_box").css({
    marginLeft: tc_wid * -1 + "px",
    marginTop: tc_hgt * -1 + "px"
  });
});

使用单击回调函数的函数表达式:

var action = function(e) {
    $(e).fadeIn(200);
    var tc_hgt = $(e).find(".popup_box").height() / 2;
    var tc_wid = $(e).find(".popup_box").width() / 2;
    if ($(e).hasClass(".popup_box")) $(e).css({marginLeft: tc_wid * -1 + "px", marginTop: tc_hgt * -1 + "px"});
};    

$(".tc_banzhu, .tc_ban, .tc_banner").click(function() {
    action(this);
});
链接地址: http://www.djcxy.com/p/83468.html

上一篇: jQuery的多元素变量事件处理程序

下一篇: 如何在不同的选择器中重用jQuery代码?