2012-04-28 54 views
0

我想首先感谢任何能够帮助我压缩这段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在弹出窗口中打开相同的#图像ID。

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

杰克

+2

是什么阻止你使用一个循环? – Claudiu 2012-04-28 00:56:48

+1

首先用$替换jQuery。 – alt 2012-04-28 00:58:15

+0

我使用jQuery而不是$来防止与Prototype冲突。 – 2012-04-28 11:49:21

回答

2
$('[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'); 
+0

这就是我所追求的。它适用于ID为1,2,3的前3项,然后我跳到项目50并且不起作用。任何想法为什么? 编辑:它不适用于9以上的任何ID(双数字) - 是否有可能改变这种情况? – 2012-04-28 08:59:28

+0

@JackClarke - 我的答案更新了两位数字,实际上它会在'-'后面的任何数字! – adeneo 2012-04-28 10:21:20

4

你的功能看起来都大同小异的,这是你应该移到这个功能出来弄成一个线索,可以称之为:

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

yay部分应用 – 2012-04-28 01:16:41

+0

但是,这仍然重复安装事件处理程序三次的代码,而不是创建处理所有三个对象的单个事件处理程序(请参阅其他答案)。 – jfriend00 2012-04-28 03:01:05

0

没有上下文很难说,但是每个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(); 
}); 
3

你可以:

  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'); 
});