html 子页面获取父页面下拉菜单选中的值用js前端用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/fjZN 著作权归作者所有。请勿转载和采集!