I have a div that is labeled "Add Comment" that expands a div area that displays a textarea for adding comments.

The div is in a partial view that is placed between a for each loop. Which create multiple instance of the div class="slide". So, when $('div.slide').click is triggered it opens all instance of comments.

If I attach id to each class="slide" Ex: class="slide1",class="slide2", etc..., how do I edit the javascript below to open only that specific div?

Jquery

<script type="text/javascript">
    $(document).ready(function () {
        // Hide the "view" div.
        $('div.view').hide();
        // Watch for clicks on the "slide" link.
        $('div.slide').click(function () {
            // When clicked, toggle the "view" div.
            $('div.view').slideToggle(400);
            return false;
        });
    });
</script>

parent view

@foreach (var post in Posts)
                {
                <div class="post">@Html.DisplayFor(modelItem => post.Message)</div>  
                <div>@Html.Partial("_Comment")</div>
                }

partial view "_Comment"

<div class="slide" style="cursor: pointer;">Add Comment</div>
<div class="view"> 
 <form method="post" id="commentForm"                       
      action="@Url.Action("AddComment")">                  

    @Html.TextArea("Comment", new { rows = 5, cols = 50 })   
    <br />
    <input type="submit" value="Add Comment" />
</form>
</div>
有帮助吗?

解决方案

No need to resort to ids.

If you structure is as in your question you can do

$(document).ready(function () {
    // Hide the "view" div.
    $('div.view').hide(); // maybe this should be handled by CSS rules 
    // Watch for clicks on the "slide" link.
    $('div.slide').click(function () {
        // When clicked, toggle the "view" div.
        $(this).next().slideToggle(400);
        return false;
    });
});

Also i would remove the .hide() part and use css for that

.view{
    display:none;
}

Example at http://jsfiddle.net/gaby/bhhMC/

其他提示

How about assigning that instance as the function's argument?

$('div.slide').click(function (this) {
    this.next().doSomething();
    ...
});

http://api.jquery.com/next/

Assuming that the structure of your html code will always be:

slide_1
view_1
slide_2
view_2
slide_3
view_3
...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top