2015-04-20 92 views
0

我需要这个小jQuery函数适用于:适用jQuery的功能,多个div

$(function(){ 
     $('.trigger').click(function(){ 
      $('.img-popup').fadeIn(500); 
      $('.overlay').fadeIn(500); 
     }); 
     $('.overlay').click(function(){ 
      $('.img-popup').fadeOut(500); 
      $('.overlay').fadeOut(500); 
     }); 
    }); 

了一系列的div:

<td class="result" > 
    <div class="trigger"><b>Show image 1</b></div> 
    <div class="overlay"></div> 
    <div class="img-popup"> 
     <img src="imageurl-1"> 
    </div> 
</td> 
... 
<td class="result" > 
    <div class="trigger"><b>Show image 2</b></div> 
    <div class="overlay"></div> 
    <div class="img-popup"> 
     <img src="imageurl-2"> 
    </div> 
</td> 

什么可能是最好的方法?

我觉得我应该在某处使用.each(),但是如何才能使用.overlay类和相关的.img-popup显示相关的div?

或者我可以改变$('.trigger').click(function()并让它只取最近的.img-popup div?

在此先感谢。

+1

你尝试过使用$(这个)选择器,当你通过每个div循环? – Alex

+1

鉴于您当前的代码,您只需更新'$('。img-popup')'和$('。overlay')'在它们之前使用'$(this).parent()'。例如,'$(this).parent()。find('.overlay')' – Huangism

回答

2

您可以使用这样的事情参考权IMG:

$(".trigger").click(function(){ 
    $(this).siblings('.img-popup').fadeIn(500); 
    $(this).siblings('.overlay').fadeIn(500); 
} 
$(".overlay").click(function(){ 
    $(this).siblings('.img-popup').fadeOut(500); 
    $(this).siblings('.overlay').fadeOut(500); 
} 
1

你并不需要循环使用each(),只要使用$(this)与jQuery的点击的按钮和家长的选择找到.img-popup.overlay

$(function(){ 
    $('.trigger').click(function(){ 
     var element = $(this), parent = element.parent(".result"), 
      img_popup = parent.find('.img-popup'), 
      overlay = parent.find('.overlay'); 
     img_popup.fadeIn(500); 
     overlay.fadeIn(500); 
    }); 
    $('.overlay').click(function(){ 
     var element = $(this), parent = element.parent(".result"), 
      img_popup = parent.find('.img-popup'); 
     img_popup.fadeOut(500); 
     element.fadeOut(500); 
    }); 
}); 
1

对于给定的代码,你可以只使用siblings() 因此,点击处理程序的内部使用这些目标

$(this).siblings('.img-popup'); 
$(this).siblings('.overlay'); 

如果您的HTML变得更加复杂,你可以使用.closest()得到结果父,像这样

var $result = $(this).closest('.result'); 
$result.find('.img-popup'); 
$result.find('.overlay'); 
0

另一种方式:

$('.trigger').click(function(){ 
    $(this).parent().children('.overlay').eq(0).fadeIn(500).parent().children('.img-popup').eq(0).fadeIn(500); 
}); 

$('.overlay').click(function(){ 
    $(this).fadeOut(500).parent().children('.img-popup').eq(0).fadeOut(500); 
});