【问题标题】:laravel {{ $loop->index }} & jquery count++laravel {{ $loop->index }} & jquery count++
【发布时间】:2021-12-25 21:20:57
【问题描述】:

使用Laravel刀片模板,有没有办法在foreach中包含一个变量并每次增加,或者更好的方法是什么?

<!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">
    @foreach($colors as $color)
        <div id="showFilters">
            <input type="text" id="name" class="form-control mb-5" name="filters[{{ $loop->index }}][name]" value="{{ $color->color_code }}">
        </div>
    @endforeach
    <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>
    let count = 0;
    $('#addFilter').click(function () {
        count++;
        let html = '<input type="text" id="name" class="form-control mb-5" name="filters['+count+'][name]">';
        $('#showFilters').append(html);
    });
</script>
</body>
</html>

【问题讨论】:

  • 仅供参考,这是无效代码。您有多个具有相同id="showFilters" 的元素。 id 属性必须是唯一的

标签: jquery laravel


【解决方案1】:

是的,这是可能的。如果您有一个普通的集合/数组,则键等于索引,您可以像这样编写foreach 循环:

@foreach($colors as $key => $color)

然后像这样使用它:name="filters[{{$key}}][name]"

如果你有一个命名数组,你可以使用 for(each) 循环并包含一些 php @php 来定义和增加一个变量。

@php
  $counter = 0;
@endphp
@foreach($colors as $color)
  .....
  @php
    $counter++;
  @endphp
@endforeach

您还需要创建独特的 ID,例如:id="name-{{$key}}"。 因此,在您的 jquery 代码中,您可以从 id 中获取正确的密钥。或者您可以查看数据属性。

【讨论】:

猜你喜欢
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2017-03-11
  • 1970-01-01
  • 2019-04-11
  • 2019-10-06
相关资源
最近更新 更多