springboot thymeleaf的頁面中,設置屬性,一般都是使用th:text,這樣的確是可以設置比如a的屬性或者p等等的屬性,現在我循環遍歷,顯示多個菜單的時候,我需要增加一個自定義的屬性,以便於點擊的時候能夠傳遞參數,所以想到html中的data-ceshi,類似於這樣的自定義屬性,thymeleaf還真提供了這種形式,參考國外的問答網址如下
https://stackoverflow.com/questions/24411826/using-data-attribute-with-thymeleaf:
//其中data-el_id這個就是自定義的屬性,你可以定義成任何你想要的格式比如data-ceshi,然後在js文件中使用jquery的$(this).data('ceshi')獲取到
<div th:attr="data-el_id=${element.getId()}">
XML rules do not allow you to set an attribute twice in a tag, so you can't have more than one th:attr in the same element.
Note: If you want more that one attribute, separate the different attributes by comma:
<div th:attr="data-id=${element.getId()},data-name=${element.getName()}">
成功從js中獲取到自定義data的標籤屬性.我的界面如下:
<ul class="nav nav-second-level collapse">
<li th:each="cmenu : ${menu.children}">
<a class="menuItem" th:text="${cmenu.menuName}" th:href="@{${cmenu.url}}" th:attr="data-menuid=${cmenu.menuId}" >二級菜單</a>
</li>
</ul>
$.modal.loading("數據加載中,請稍後...");
// 獲取標識數據
var dataUrl = $(this).attr('href'),
dataIndex = $(this).data('index'),
menuName = $.trim($(this).text()),
flag = true;
//獲取點擊的menuId,2018年7月10日13:39:25
var menu_id = $(this).data('menuid');
console.log("獲取到的菜單ID爲"+menu_id);
運行結果如下: