压缩Javascript / jQuery代码
我想首先感谢任何可以帮助我压缩这段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。
再次感谢任何可以提供帮助的人。
插口
$('[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');
你的函数看起来几乎都是一样的,这是一个线索,你应该把这个function转移到可以调用的东西:
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"));
您可以:
- 使用公共事件处理程序将多个对象组合到选择器中
- 使用
this
来引用触发事件的对象 - 从生成事件的对象的id派生图像ID。
这使您可以使用一段代码来处理所有三个对象的操作:
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'); });
如果没有上下文,很难说,但是每个pitem
都必须有一个唯一的ID吗? 为什么不使用CSS类而不是像这样的ID:
...
然后使用jQuery中的类选择器一次性添加所有这些的单击function:
$(".pitem").click(function(e) { var currentItem = e.target; ... e.preventDefault(); });