简体   繁体   English

通过单击带有 jquery 的按钮在循环中显示图像?

[英]Display the image in the loop by clicking the button with jquery?

I have a loop that displays three images this loop:我有一个循环显示三个图像这个循环:

 @foreach (var item in Model)
                            {
                                <img id="img" src="@item.imgname" />
                            }

so I have three buttons:所以我有三个按钮:

<div class="box-img">
     <a class="btn btn-success">First pic</a>
     <a class="btn btn-info">second pic</a>
     <a class="btn btn-primary">third pic</a>
 </div>

When the "First pic" tag is clicked, the first image is displayed and the "second pic" tag is clicked, the second image is displayed and...单击“第一张图片”标签时,会显示第一张图片,点击“第二张图片”标签时,会显示第二张图片,然后...

How can I doing?我该怎么办?

Display the image in the loop by clicking the button with jquery通过单击带有 jquery 的按钮在循环中显示图像

You can refer to the following code snippet to achieve the requirement.您可以参考以下代码片段来实现需求。

HTML code HTML代码

<div id="img_container">
    @foreach (var item in Model)
    {
        <img id="img" src="@item.imgname" />
    }
</div>

<hr />

<div class="box-img">
    <a class="btn btn-success">First pic</a>
    <a class="btn btn-info">second pic</a>
    <a class="btn btn-primary">third pic</a>
</div>

jQuery code jQuery代码

$(function () {
    //hide all these three images
    $("div#img_container img").hide();

    //display the first image
    $("div#img_container img:nth-child(1)").show();

    //display the first image
    $("a.btn-success").click(function () {
        $("div#img_container img").hide();

        $("div#img_container img:nth-child(1)").show();
    });

    //display the second image
    $("a.btn-info").click(function () {
        $("div#img_container img").hide();

        $("div#img_container img:nth-child(2)").show();
    });

    //display the third image
    $("a.btn-primary").click(function () {
        $("div#img_container img").hide();

        $("div#img_container img:nth-child(3)").show();
    })
})

Test Result测试结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM