简体   繁体   中英

A simple show or hide item.text button

I have a mvc 5 project using a database. In my project I have a Blog-page. This page is loaded using a controller. In the page I dynamically create a list of items (blogitems) using a simple '@foreach(var item in collection). Each item has an id (off course), a title and a description.

    @foreach (var item in Model.VmBlogItems)
    {
        <div class="allblogs">
            <div class="blogtitle">
                <h4>@item.Title</h4>
            </div>
            <div id="allblogcontent">
                @item.Description
            </div>
            <a id="moreless" href="">Lees meer</a>

        </div>
    }

My question now is how I can create a button so that when clicked on it the description is hidden or shown.

I also wrote some jquery:

<script type="text/javascript">
    //when ready
    $(function () {
        $('#allblogcontent').hide();

        $('#moreless').click(function () {
            $('#allblogcontent').toggle();
        });
    });
</script>

However when I try this, all my items show or hide the Description.

Does anybody know how I make sure that only the Description of the selected item is shown or hidden? I just spend 6 hours reading, trying and sadly enough failing to make it work. I could use some help.

First you modify the markup so each description tag has a unique id attached to it, and the corresponding button has a reference to that id

@{
   int i=0;
}
@foreach (var item in Model.VmBlogItems)
{
    i++;

    <div class="allblogs">
        <div class="blogtitle">
            <h4>@item.Title</h4>
        </div>
        <div id="allblogcontent@i" class='someclass'>
            @item.Description
        </div>
        <a id="moreless" href="" data-desc-id='allblogcontent@i'>Lees meer</a>

    </div>

}

Your code can figure out which is which now.

<script type="text/javascript">
    //when ready
     $(function () {
        $('.someclass').hide();

        $('#moreless').click(function () {
            $('#' + $(this).attr('data-desc-id')).toggle();
        });
    });
</script>

A footnote

This approach will make static references between the tags, so you can move the markup around if you like. The other two solutions shown here, so far, will break if you change the order of the tags.

Just change the below section from

$('#moreless').click(function () {
    $('#allblogcontent').toggle();
});

to

$('#moreless').click(function () {
    $(this).siblings('#allblogcontent').toggle();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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