#html #thymeleaf
#HTML #thymeleaf
Вопрос:
Я намереваюсь получить объект внутри одной из строк таблицы, чтобы я мог переслать его в форму с помощью простой функции JavaScript. Я не знаком с jQuery, поэтому я подумал, что выберу максимально простой подход. Я думал сделать это, используя атрибут th:data * в сочетании с th:each, вот так:
<tr th:each="employee : ${empDetailsList}" th:data-employee="${employee}">
<td scope="row" th:text="${employee.id}">ID</td>
<td scope="row" th:text="${employee.firstName}">firstName goes here</td>
<td scope="row" th:text="${employee.lastName}">lastName goes here</td>
<td scope="row" th:text="${employee.email}">email goes here</td>
<td scope="row" th:text="${employee.username}">user name goes here</td>
<td th:data-employee="${employee}">
<button type="button" class="btn btn-info" th:onclick="showEditForm(this.getAttribute('data-employee'));">Details</button>
</tr>
Я также попробовал этот подход, переместив th: data-employee из тега ‘tr’ в тег ‘td’, но результат тот же:
<tr th:each="employee : ${empDetailsList}">
...
<td th:data-employee="${employee}">
<button type="button" class="btn btn-info" th:onclick="showEditForm(this.getAttribute('data-employee'));">Details</button>
</tr>
Функция JS:
function showEditForm(employee){
console.log('Employee object here: ');
console.log(employee.firstName);
console.log(employee.lastName);
}
Как я уже упоминал, я получаю один и тот же результат в обоих случаях. Ответ консоли браузера:
Employee object here:
TypeError: employee is null
Итак, что я здесь делаю не так?
Комментарии:
1. Причина, по которой он не работает, заключается в том, что
th:data-employee="${employee}"
не записывает employee как объект javascript. Он записывает java по умолчаниюtoString()
— что-то вродеcom.whatever.Customer@6d06d69c
(что вы сможете легко проверить, просмотрев исходный код в своем браузере). Я не знаю хорошего способа выполнить то, что вы хотите.2. Спасибо, Metroids! Ваш ответ помог мне решить проблему.
Ответ №1:
Это сработало для меня:
<p th:each="testScript:${testScripts}">
<a th:href="|/scripts/start/${testScript}|" th:text="'Start ' ${testScript}"/>
<a th:href="|/scripts/stop/${testScript}|" th:text="'Stop' ${testScript}"/>
<button id="searchButton" name="searchButton" th:onclick="start(this.getAttribute('data_p1'));" type="button"
th:data_p1="|${testScript}|"
th:text="|${testScript}|">Start</button>
</p>