压缩Javascript/jQuery代码

Condensing Javascript/jQuery Code

本文关键字:代码 jQuery Javascript 压缩      更新时间:2023-09-26
首先,

我要感谢任何可以帮助我压缩这段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。

再次感谢任何可以提供帮助的人。

千斤顶

你的函数看起来都差不多,这是一个线索,你可能应该将该功能移到可以调用的东西中:

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"));

您可以:

  1. 使用公共事件处理程序将多个对象合并到选择器中
  2. 使用 this 引用触发事件的对象
  3. 从生成事件的对象的 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');
});
$('[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');

没有上下文很难说,但是是否有必要为每个pitem都有一个唯一的 ID?为什么不使用CSS类而不是像这样的ID:

<div class="pitem">
<div id="image1"><img ... /></img>
</div>
...
<div class="pitem">
<div id="image3"><img ... /></img>
</div>

然后使用 jQuery 中的类选择器一次性添加所有点击功能:

$(".pitem").click(function(e) {
  var currentItem = e.target;
  ...
  e.preventDefault();
});