springboot thymeleaf 需要使用data-*,自定义属性,获取值
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 cant 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);
运行结果如下: