压缩Javascript/jQuery代码
首先,我要感谢所有能够帮助我压缩这段Javascript/jQuery代码的人压缩Javascript/jQuery代码,javascript,jquery,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("
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在弹出窗口中打开相同的图像ID
再次感谢任何能帮忙的人
Jack您的函数看起来几乎相同,这表明您可能应该将该功能移到可以调用的地方:
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"));
没有上下文很难说,但是每个pitem是否需要有一个唯一的ID?为什么不使用CSS类而不是像这样的ID:
<div class="pitem">
<div id="image1"><img ... /></img>
</div>
...
<div class="pitem">
<div id="image3"><img ... /></img>
</div>
你可以:
使用公共事件处理程序将多个对象合并到选择器中
使用此选项可引用触发事件的对象
从生成事件的对象的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');
});
是什么阻止了您使用循环?首先用$替换jQuery。我使用jQuery而不是$来防止与原型冲突。但是,这仍然会重复代码以安装事件处理程序三次,而不是创建一个处理所有三个对象的单一事件处理程序。请参阅其他解决方案。这就是我想要的。它适用于ID为1,2,3的前3个项目,但是我跳到项目50,它不起作用。知道为什么吗?编辑:它不适用于任何超过9个双位数的ID-有可能改变吗?@JackClarke-更新了我的答案,使其也采用两位数,实际上它将采用-之后的任何位数!
$('[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');
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');
});