Hide/unhide each photo individually in foreach statement
P粉211600174
P粉211600174 2024-02-03 22:53:06
0
1
423

Update: It works with me using @Exildur solution, but when I refresh the page, the hidden photos are visible again :S.

I have a list of projects, each with its own photo. I need to add a hide/show photo button for each photo. The problem is when I use the js function with the id it only hides/shows the first photo because the Id must be unique. This is the code:

foreach (var item in Model.AttachmentsList)
{
   <div style=" display: inline-block;  width: 400px; margin:10px;">
                    
      @Html.Raw("<a href='../../" + item.FileUrl + "' alt='img'> <img  src='../../" + item.FileUrl + "'  > </a>")
                   
    </div>

    <button id="btn_photo">Hide/Show Photo</button>
               

 }

P粉211600174
P粉211600174

reply all(1)
P粉349222772

You can create a unique identifier for each photo using the item index in the list appended to the name. For example:

foreach (var item in Model.AttachmentsList)
{
    var index = Model.AttachmentsList.IndexOf(item);
    
@Html.Raw(" ")
} sssccc

This will create a unique ID for each photo, such as photo_0, photo_1, etc.

The button has an onclick attribute which calls the togglePhoto() function passing the item's index as a parameter, then gets the corresponding photo and toggle its visibility by setting the display style to block/none.

Update: Persistence after page refresh

As requested, to include persistence of hidden/visible images across page refreshes, I've added the ability to use browser storage to record which images are visible or invisible:

foreach (var item in Model.AttachmentsList)
{
    var index = Model.AttachmentsList.IndexOf(item);
    var display = localStorage.getItem('photo_' + index + '_display') || 'block';
    
@Html.Raw(" ")
} sssccc

In the above example, the "display" style value for each photo will be retrieved from localStorage. If not present, it will default to "blocked" (visible).

The togglePhoto() function stores the updated display value in localStorage whenever the button is clicked.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!