简体   繁体   English

如何在 js 文件中使用 foreach 循环?

[英]How can use foreach loop in js file?

$(document).ready(function() {
        $("form").on("click", ".addRow", function(){
            var ttr =   '<div class="row add tr">'+
                           '<div class="col">'+
                                '<select class="form-control single purchaseCat" name="category_id[]">'+
                                   '<option value="">Select Category</option>'+
                                   '@foreach($categories as $category)'+
                                   '<option value="{{$category->id}}">{{$category->category_name}}</option>'+
                                   '@endforeach'+
                                '</select>'+
                            '</div>'+    
                         '</div>'
            $('.invoice_table').append(ttr);
        });
    });

I'm using a dynamic dropdown.我正在使用动态下拉菜单。 If you check the image you can understand the problem is.如果您检查图像,您可以了解问题所在。 when i add new row this time foreach didn't work当我这次添加新行时,foreach 不起作用

https://i.stack.imgur.com/7ZSP5.png

The issues is most likely because the @foreach is a Laravel instruction which won't be executed inside a .js file.问题很可能是因为@foreach是 Laravel 指令,不会在 .js 文件中执行。

The simple way to do what you need is to use clone() to copy an existing row and then append() that to the DOM where required做你需要的简单方法是使用clone()复制现有行,然后 append() 到需要的 DOM

$(document).ready(function() {
  $("form").on("click", ".addRow", function() {
    let $newRow = $('div.row:first').clone();
    $newRow.find('select.purchaseCat').val(''); // reset selected option to default
    $('.invoice_table').append($newRow);
  });
});

Also, just as an aside to the question, it looks like you're using div elements to create a table , which is a little odd.此外,作为问题的旁白,看起来您正在使用div元素创建一个table ,这有点奇怪。 Remember that it's absolutely valid and correct to use a table element for tabular data.请记住,将table元素用于表格数据是绝对有效和正确的。 It's only using tables for layout that should be avoided.它只使用表格进行布局,应该避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM