JavaScript 获取父页面下拉菜单选中值并使用 Thymeleaf 显示
可以使用 JavaScript 的 'parent' 对象来获取父页面的下拉菜单选中的值,然后在子页面中使用 Thymeleaf 来显示该值。
以下是示例代码:
父页面.html:
<!DOCTYPE html>
<html>
<head>
<title>父页面</title>
</head>
<body>
<select id='mySelect'>
<option value='option1'>选项1</option>
<option value='option2'>选项2</option>
<option value='option3'>选项3</option>
</select>
<button onclick='showSelectedValue()'>显示选中值</button>
</body>
<script>
function showSelectedValue() {
var selectElement = parent.document.getElementById('mySelect');
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
alert('选中的值是:' + selectedValue);
}
</script>
</html>
子页面.html:
<!DOCTYPE html>
<html>
<head>
<title>子页面</title>
</head>
<body>
<p>父页面选中的值是:<span th:text='${selectedValue}'></span></p>
</body>
<script>
var selectElement = parent.document.getElementById('mySelect');
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
document.querySelector('span').textContent = selectedValue;
</script>
</html>
在子页面的 JavaScript 代码中,通过 'parent.document' 来获取父页面的 DOM 对象,然后可以像在父页面中一样获取下拉菜单选中的值。将该值赋给 Thymeleaf 表达式 '${selectedValue}',即可在子页面中显示父页面选中的值。
注意:在使用 'parent' 对象时需要确保子页面和父页面在同一个域名下,否则会出现跨域问题。
原文地址: https://www.cveoy.top/t/topic/objp 著作权归作者所有。请勿转载和采集!