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

Laravel Blade中PHP变量修改后无法持久生效问题

问题原因
  • 核心错误是Blade服务端渲染语法和前端JS运行时逻辑混用:你代码里写的{{ $currentIndex }}、@include()都是Laravel Blade在服务端返回页面前就执行解析的语法,不会在浏览器端用户点击按钮时重新运行。
  • 页面首次加载完成后,所有Blade语法已经被替换成静态值:{{$currentIndex}}被替换成固定数字1,@include('reservations.create-input-box-'.$currentIndex)被替换成第一步输入框的静态HTML字符串。你写在点击事件里的{{$currentIndex +=1}}根本不会在点击时执行,只是服务端渲染时就已经算完值写死在代码里了。
  • 你写的getCurrentIndex是从DOM元素类名里取索引,但因为每次替换的HTML永远是第一步的内容,DOM里的类名永远对应第一步,取出来的索引自然永远回到1。
解决方案
  • 把JS逻辑和Blade语法彻底拆分:前端的步骤状态currentIndex纯用JS变量维护,不要在JS代码块里写任何{{ }}、@include这类服务端模板语法。
  • 多步表单的实现优先选预渲染+显隐控制的方案,不需要额外写接口,逻辑最稳定:服务端渲染页面时直接把所有步骤的输入框HTML全部输出到页面,前端只做元素的显示/隐藏切换即可。
  • 修正后的可运行代码如下:

首先是Blade模板部分(HTML结构):

<div id="create-input-box">
    {{-- 预渲染所有步骤的输入框,默认仅显示第一步 --}}
    <div class="step-item step-1">@include('reservations.create-input-box-1')</div>
    <div class="step-item step-2" style="display: none;">@include('reservations.create-input-box-2')</div>
    <div class="step-item step-3" style="display: none;">@include('reservations.create-input-box-3')</div>
</div>
<button class="back-btn">上一步</button>
<button class="next-btn">下一步</button>

然后是前端JS逻辑:

const totalStep = 3
let currentIndex = 1

// 初始化按钮状态
updateButtonStatus()

// 绑定按钮点击事件
$('.back-btn, .next-btn').on('click', function (e) {
    const isNext = e.target.classList.contains('next-btn')
    // 边界判断,防止索引越界
    if (isNext && currentIndex < totalStep) currentIndex++
    if (!isNext && currentIndex > 1) currentIndex--

    // 切换步骤显隐
    $('.step-item').hide()
    $(`.step-${currentIndex}`).show()

    // 更新按钮状态
    updateButtonStatus()
})

function updateButtonStatus() {
    if (currentIndex <= 1) {
        $('.back-btn').hide()
        $('.next-btn').show()
    } else if (currentIndex === totalStep) {
        $('.back-btn').show()
        $('.next-btn').hide()
    } else {
        $('.back-btn').show()
        $('.next-btn').show()
    }
}

如果你不想提前渲染所有步骤,也可以写一个接收步骤索引、返回对应HTML的后端接口,点击按钮时发AJAX请求动态拉取对应步骤内容再渲染,但要注意绝对不能把@include直接写在JS代码里等前端触发执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 21:36:18