如何在不同的选择器中重用jQuery代码?
我在下面编写代码,区别在于选择器,所以如何在少代码中重用相似的方法? 如何使用工厂功能?
$(".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/83467.html
上一篇: how to reuse jQuery code in different selectors?
下一篇: How To call the same Method for different Elements with different IDs?