You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码实现点击reply-img仅展示最近的reply-form元素

实现点击回复图标仅显示对应回复表单的功能

问题场景

现有多个.reply-img元素,需求为点击某个回复图标时,仅展示其对应的最近.reply-form表单,同时隐藏其他所有回复表单。当前JavaScript代码点击后会显示全部表单,需修改代码实现目标效果。

原有代码

HTML(Blade模板)

<div class="comments-form">
    @foreach($comments as $comment)
    
    <div class="comments">
       ...
                            
       <div class="reply-img">
           <img src="{{asset('img/react.svg')}}" alt="">
       </div>
    </div>
    ...
    <form class='login-form mmm ml-x reply-form'></form>
    
    @endforeach
...
</div>

原有JavaScript代码

<script>
        // Get all image elements
        var images = document.querySelectorAll(".reply-img");
    
        // Attach a click event listener to each image
        images.forEach(function(image) {
            image.addEventListener("click", function() {
                // Show all forms
                var forms = document.querySelectorAll(".reply-form");
                forms.forEach(function(form) {
                    form.style.display = "block";
                });
            });
        });
    </script>

修改后的JavaScript代码

<script>
    // 获取所有回复图标元素
    const replyImages = document.querySelectorAll(".reply-img");

    // 为每个图标绑定点击事件
    replyImages.forEach(image => {
        image.addEventListener("click", function() {
            // 1. 先隐藏所有回复表单
            const allReplyForms = document.querySelectorAll(".reply-form");
            allReplyForms.forEach(form => {
                form.style.display = "none";
            });

            // 2. 定位当前图标对应的回复表单
            const commentsContainer = this.closest(".comments");
            let targetForm = null;
            let nextSibling = commentsContainer.nextElementSibling;
            
            // 遍历comments容器的后续兄弟元素,找到对应的reply-form
            while (nextSibling) {
                if (nextSibling.classList.contains("reply-form")) {
                    targetForm = nextSibling;
                    break;
                }
                nextSibling = nextSibling.nextElementSibling;
            }

            // 3. 显示目标表单
            if (targetForm) {
                targetForm.style.display = "block";
            }
        });
    });
</script>

逻辑说明

  1. 全局隐藏表单:点击图标时先将所有回复表单隐藏,避免多个表单同时显示。
  2. 定位对应表单:通过closest('.comments')找到当前图标所在的评论容器,再遍历该容器的后续兄弟元素,精准定位到属于当前评论的回复表单。
  3. 显示目标表单:将找到的对应表单设置为显示状态。

如果可以修改HTML结构,建议给每个循环项添加父容器(比如<div class="comment-item">),这样可以简化表单定位逻辑,直接用this.closest('.comment-item').querySelector('.reply-form')获取目标表单。

内容的提问来源于stack exchange,提问作者Aaron7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:15:43