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

Laravel Blade foreach如何实现变量自增 动态新增表单最优方案是什么

Blade foreach 自动递增的内置方案

Laravel Blade 的 @foreach 循环自带全局$loop变量,不需要手动声明计数器即可实现自动递增,常用属性如下:

  • $loop->index:从0开始的当前遍历索引,适合用于数组下标,就是你示例中用到的属性
  • $loop->iteration:从1开始的当前遍历次数,适合前台展示序号
  • $loop->count:当前循环的总数据条数

注意你给出的示例代码存在小问题:id="showFilters" 写在@foreach循环内部,会生成多个相同id的DOM节点,不符合规范,需要把容器移到循环外部

配合jQuery动态新增表单项的优化方案

你现在的写法存在索引冲突隐患:如果后端已经渲染了N条数据,JS里的count初始值为0,新增项的索引会和已有项重复。优化思路如下:

  • 初始计数从后端渲染的数组长度直接获取,避免索引重复
  • 抽离公共的表单项模板,避免在JS里拼接HTML,后续修改字段更方便
  • 补充重复id处理、删除功能等常用能力

优化后的完整实现代码如下:

<!doctype html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" type="image/x-icon"/>
    <link href="{{ asset('themes/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ asset('themes/fontawesome/css/all.min.css') }}" rel="stylesheet">
    <link href="{{ asset('themes/css/style.css') }}" rel="stylesheet">
    <title>Test</title>
</head>
<body>
<div class="d-flex min-vh-100 justify-content-center align-items-center flex-column">
    <!-- 容器移到循环外部 -->
    <div id="showFilters">
        @foreach($colors as $color)
            <div class="filter-item d-flex align-items-center mb-5">
                <input type="text" class="form-control" name="filters[{{ $loop->index }}][name]" value="{{ $color->color_code }}">
                <button type="button" class="btn btn-danger ms-2 delete-filter">删除</button>
            </div>
        @endforeach
    </div>
    <a id="addFilter" class="bg-primary text-white pt-2 pb-2 pe-3 ps-3 rounded-circle cursor-pointer">
        <i class="fas fa-plus"></i>
    </a>
</div>
<script src="{{ asset('themes/js/bootstrap.bundle.min.js') }}"></script>
<script src="{{ asset('themes/js/jquery-3.6.0.min.js') }}"></script>
<script>
    // 初始计数直接取后端数组长度,100%避免索引冲突
    let count = {{ count($colors) }};
    $('#addFilter').click(function () {
        // 用模板字符串简化写法,不用手动拼接HTML
        let html = `
            <div class="filter-item d-flex align-items-center mb-5">
                <input type="text" class="form-control" name="filters[${count}][name]">
                <button type="button" class="btn btn-danger ms-2 delete-filter">删除</button>
            </div>
        `;
        $('#showFilters').append(html);
        count++;
    });

    // 绑定动态生成元素的删除事件
    $(document).on('click', '.delete-filter', function () {
        $(this).closest('.filter-item').remove();
    });
</script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:45:03