簡體   English   中英

使用 Thymeleaf 模板在 jQuery 內部循環 Java Object

[英]Loop through Java Object inside jQuery using Thymeleaf template

我是 Java 和 thymeleaf 的新手。使用 jquery 和 thymeleaf,我嘗試動態生成 html 行。

是否有可能在 jquery function 中循環遍歷 thymeleaf 標簽? (因為Thymeleaf是java的服務端模板引擎)

如果沒有,我如何循環遍歷 jquery 中的facilities變量。

Controller:項目控制器.java

@GetMapping("/create")
public String create(Model model){
    model.addAttribute("project", new Project());
    model.addAttribute("categories", categoryService.getAllCategories());
    model.addAttribute("features", featureService.getAllFeatures());
    model.addAttribute("facilities", facilityService.getAllFacilities());
    model.addAttribute("investors", investorService.getAllInvestors());

    return CREATE_PAGE;
}

查看:創建.html

 $("#add-new-row").on('click', function () {
        var html = "";

        html += `<tr>
                    <td>
                        <select name="facilities[][id]" class="form-control">
                            <option value="" disabled selected>Select facility</option>
                            <option th:each="facility : [(  ${facilities} )]" th:value="${facility.id}" th:text="${facility.name}"></option>
                        </select>
                    </td>
                    <td>
                        <input type="number" step="any" name="facilities[][distance]"
                               placeholder="Distance (Km)"
                               class="form-control">
                    </td>
                    <td>
                        <button type="button" class="btn btn-warning remove-current-row"><i
                                class="fa fa-times"></i>
                        </button>
                    </td>
                </tr>`;

        $("#append-new-facility").append(html);
    });

    $(document).on('click', ".remove-current-row", function () {
        $(this).closest('tr').remove();
    });

看法

這里的設施列表應該是動態的,並作為對象數組接收。

錯誤

Uncaught ReferenceError: facility is not defined

請提及問題是否需要更多詳細信息。 歡迎任何幫助。

您可以通過將設施作為數組傳遞給您的 JavaScript 並在 Jquery 中構建它來執行此操作。無法在 JavaScript 中解析 Thymeleaf 標簽。

例如:

let facilities = /*[[${facilities}]]*/ [];
let select = $('<select name="facilities[][id]" class="form-control" />');
select.append('<option value="" disabled selected>Select facility</option>');
facilities.forEach(function (facility) {
  select.append($('<option></option>').attr('val', facility['id']).text(facility['name']));
});
html += $('<div>').append(select).html();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM