首先,我想要感谢那些能帮助我压缩这段Javascript/jQuery代码的人。
jQuery(function() {
jQuery('#pitem-1').click(function(e) {
jQuery("#image-1").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-1").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('#pitem-2').click(function(e) {
jQuery("#image-2").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-2").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('#pitem-3').click(function(e) {
jQuery("#image-3").lightbox_me({centered: true, onLoad: function() {
jQuery("#image-3").find("input:first").focus();
}});
e.preventDefault();
});
jQuery('table tr:nth-child(even)').addClass('stripe');
});基本上,每个#pitem-ID都会在弹出窗口中打开相同的#image-ID。
再次感谢任何能提供帮助的人。
杰克
发布于 2012-04-28 09:06:16
$('[id^="pitem-"]').click(function(e) {
var numb = this.id.split('-')[1];
$("#image-"+numb).lightbox_me({centered: true, onLoad: function() {
$(this).find("input:first").focus();
}
});
e.preventDefault();
});
$('table tr:nth-child(even)').addClass('stripe');发布于 2012-04-28 08:58:50
您的函数看起来几乎都一样,这是一个提示,您可能应该将该功能移到可以调用的东西中:
function createHandler(id) {
return function (e) {
$(id).lightbox_me({centered: true, onLoad: function() {
$(id).find("input:first").focus();
}});
e.preventDefault();
}
};然后,您可以使用:
$('#pitem-2').bind('click', createHandler("#image-2"));发布于 2012-04-28 09:22:02
您可以:
this引用触发事件的对象这使您可以使用一段代码来处理所有三个对象的操作:
jQuery(function() {
jQuery("#pitem-1, #pitem-2, #pitem-3").click(function() {
var image$ = $("#" + this.id.replace("pitem", "image"));
image$.lighbox_me({centered: true, onLoad: function() {
image$.find("input:first").focus();
}});
e.preventDefault();
});
jQuery('table tr:nth-child(even)').addClass('stripe');
});https://stackoverflow.com/questions/10359594
复制相似问题