我有一个 ASP.NET mvc 项目,其中有添加注释的功能。我希望在单击回复按钮时,创建 View 会在该特定评论之后的空间加载。 Reply() 函数用于加载它。但是,即使我单击任何评论下方的回复按钮,创建 View 也会加载到第一个评论之后的空间中。下面的代码位于 ShowComments View 中,我在任何其他 View 的末尾呈现该 View
@foreach (var item in Model)
{
//code to display other properties of comment object
<section onclick="Reply()" class="btn btn-default">
Reply
</section>
<div id="ReplyCommentBox">
</div>
}
回复函数有以下行
$('#ReplyCommentBox').load('http://localhost:5414/Comments/Create/');
请帮助找出解决方案,以便在单击回复按钮的评论之后立即加载创建 View 。
最佳答案
@foreach (var item in Model)
{
//code to display other properties of comment object
<section class="btn btn-default reply-btn">
Reply
</section>
<div class="ReplyCommentBox">
</div>
}
在 jQuery 中,当您通过 id 访问元素时,它会获取具有匹配选择器的第一个元素。这就是始终添加到第一行的原因。在您的情况下,您必须使用 class 而不是 id,因为同一类有多个元素
$(document).on('click', '.reply-btn', function(){
var replyBox = $(this).next('.ReplyCommentBox');
var boxContent = $.trim(replyBox.html())
if(boxContent){
# if the `ReplyCommentBox` has content empty it
replyBox.html('');
}else{
# no content, so load the div with content
replyBox.load('http://localhost:5414/Comments/Create/');
}
})
这将检查 ReplyCommentBox
中是否有任何内容。如果它有任何内容,它将删除它,否则它将加载评论 View 。
关于javascript - Ajax 调用仅在第一行之后加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36277315/