简单的jQuery Each函数



我有一个codePen,它有一个简单的设置。我正在尝试单击相应的按钮以显示相应的图像。我们有一个"红框",应该只显示第一个图像,而"绿框"应该只显示第二个图像。

我知道我可以通过简单的javascript点击来做到这一点,但我会在页面上有很多框,我想做一些每个循环,知道我点击了哪个方块,以显示与该方块相关的正确图像。

我该如何正确设置,这样我就可以有一个点击功能,知道我点击了哪个方块来显示正确的图像?我为每个图像添加了一些"数据"属性,想也许我可以用每个函数引用这些属性。。。我只是不知道该怎么做!

这是代码笔,看看我的意思是

//reveal the appropriate large image here with javascript.
//Maybe I can use an array to choose the correct image?
//But how will the click function know which one to reveal ?
//Maybe an 'each' function can help,
//but I'm not sure how to set that up properly...
var correctImage = ["#img1", "#img2"];
$(".box").click(function( event ) {
  var largeImages = new TimelineMax();
  largeImages.set(correctImage, {css:{display: "block"}})
        .from(correctImage, 1, {autoAlpha:0, ease:Sine.easeOut});
});
// just a reset button here
$(".reset").click(function( event ) {
  var largeImages2 = new TimelineMax();
  largeImages2.set(correctImage, {clearProps: "all"});
});

这很简单。我将在下面添加一个带有javascript的html示例,以演示如何知道单击了哪个按钮。

.my_image {
    display: none;
}
<a class="my_button" data-id="1">Test button 1</a>
<a class="my_button" data-id="2">Test button 2</a>
<a class="my_button" data-id="3">Test button 3</a>
<img class="my_image" data-id="1" src="http://blog.jelanieshop.com/wp-content/uploads/2012/07/girl-laughing.jpg" />
<img class="my_image" data-id="2" src="http://thumbs.dreamstime.com/x/laughing-girl-1938830.jpg" />
<img class="my_image" data-id="3" src="http://dailyplateofcrazy.com/wp-content/uploads/2014/09/Beautiful-Girl-Laughing.jpg" />

神奇之处:

$(".my_button").click(function(){
    $(".my_image[data-id="+$(this).attr("data-id")+"]").show();
});

我希望这能回答你的问题,或者至少对你有所帮助。

最新更新