javascript - Ajax 调用仅在第一行之后加载数据

标签 javascript jquery asp.net ajax

我有一个 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/

相关文章:

asp.net - 为什么我的自定义 404 错误处理程序在部署到 Web 服务器后不起作用

asp.net - 无特殊字符加解密

javascript - 滑动拼图(网页游戏)- 过渡

c# - 在哪里存储应用程序全局设置?

javascript - navigator.mediaDevices.enumerateDevices() 不在 Firefox 上显示设备标签

javascript - 在 Javascript 中保存切换元素和本地存储

javascript - 单击固定顶部菜单后防止导航到页面顶部

javascript - knockout JS建议

javascript - 动画 View 中出现错误 : Exception in HostFunction: Malformed calls from JS: field sizes are different.

javascript - 显示和隐藏 javascript 函数的问题