Thymeleaf foreach循环,内部带有按钮事件

时间:2018-06-20 02:29:51

标签: javascript html spring-boot thymeleaf

我使用Thymeleaf foreach遍历所有帖子,每个帖子都有一个“评论”按钮。单击此“评论”按钮后,我想显示评论列表。

The default is hidden

以下是我的代码:

            <div th:each="post:${posts}">
                <div class="panel panel-default" th:object="${post}">
                    <div class="panel-body">
                        <p th:text="*{user.username}">username</p>
                        <p th:text="*{createTime}">time</p>
                        <p th:text="*{content}">content</p>
                        <div>
                            <form th:action="@{/posts/liked/input}" method="post"
                                style="display: inline">
                                <input type="hidden" name="postId" id="postIdId"
                                    class="form-control" th:value="*{id}">
                                <button type="submit" class="btn btn-primary">like</button>
                            </form>
                            <button class="btn btn-primary commentBt"
                                style="display: inline">Comment</button>
                        </div>
                    </div>

                    <!--  This is the part I want to show after click Comment -->
                    <div style="display: none">
                        <form th:action="@{/posts/comment/input}" method="post">
                            <textarea class="form-control" name="content" id="contentId"
                                rows="1"></textarea>
                            <input type="hidden" name="postId" id="postIdId"
                                class="form-control" th:value="*{id}">
                            <button type="submit" class="btn btn-primary">Reply</button>
                        </form>
                        <div th:each="comment:*{comments}">
                            <div th:object="${comment}">
                                <p th:text="*{content}">content</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

如何在foreach循环中执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以使用js进行操作,以下是示例代码。

首先,您需要添加onclick来提交按钮:

<button  class="btn btn-primary commentBt"
                            style="display: inline" onclick="showDiv()">Comment</button>

然后,获取隐藏的div并编辑功能showDiv以显示div。

  <!-- set id -->
  <div id="test" style="display: none">

    <script>
    <!-- function to change display to block -->
    function showDiv(){
        var div = document.getElementById("test");
        div.style.display="block";
    }
</script>

希望这对您有帮助!