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

Thymeleaf双向Fragment实现及登录弹窗失效问题求助

Thymeleaf双向Fragment复用后登录弹窗失效排查求助

我正在用Thymeleaf实现通用模板复用:让MainTemplate作为基础模板,被main.html、bmi.html等多个页面复用,子页面的自定义内容通过replace/insert语法替换到模板里的mainTemplateElement片段中。目前模板复用的逻辑已经跑通,但页面上的登录按钮弹窗完全没反应,点击后看不到弹窗弹出。

下面是相关代码片段,麻烦帮忙排查问题:

MainTemplate 代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${pageTitle}">默认标题</title>
    <link rel="stylesheet" th:href="@{/css/modal.css}">
</head>
<body>
    <!-- 顶部导航栏 -->
    <header>
        <button id="loginBtn">登录</button>
    </header>

    <!-- 登录弹窗容器 -->
    <div id="loginModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h3>用户登录</h3>
            <form id="loginForm">
                <div>
                    <label>用户名:</label>
                    <input type="text" name="username" required>
                </div>
                <div>
                    <label>密码:</label>
                    <input type="password" name="password" required>
                </div>
                <button type="submit">提交登录</button>
            </form>
        </div>
    </div>

    <!-- 子页面内容占位片段 -->
    <div th:fragment="mainTemplateElement"></div>

    <script th:src="@{/js/modal.js}"></script>
</body>
</html>

子页面示例(main.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{MainTemplate :: html}">
<head>
    <title>首页</title>
</head>
<body>
    <div th:replace="~{MainTemplate :: mainTemplateElement}">
        <h1>欢迎访问首页</h1>
        <p>这是首页的自定义内容区域</p>
    </div>
</body>
</html>

弹窗CSS(modal.css)

/* 弹窗背景层 */
.modal {
    display: none;
    position: fixed;
    z-index: 999;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

/* 弹窗内容区 */
.modal-content {
    background-color: #fff;
    margin: 12% auto;
    padding: 24px;
    border-radius: 8px;
    width: 90%;
    max-width: 400px;
    position: relative;
}

/* 关闭按钮 */
.close {
    position: absolute;
    top: 12px;
    right: 16px;
    font-size: 24px;
    cursor: pointer;
    color: #666;
}

.close:hover {
    color: #000;
}

已确认的信息

  • 子页面内容能正确替换到mainTemplateElement片段中,模板复用逻辑正常
  • 弹窗的CSS、JS文件路径正确,浏览器控制台没有404报错
  • 点击登录按钮后,控制台没有任何JS报错信息

现在完全不知道问题出在哪,希望能帮忙分析可能的原因,以及给出修复方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:17:27