我正在构建一个基于 Spring MVC 的 Web 应用程序,我将在其中使用几个下拉菜单。
我试图实现的是,当用户选择其中一个可用选项时,该选项的描述将出现在 select-tag 旁边。
<select name="userType">
<c:forEach items="${userTypes}" var="userType">
<option>${userType.userType}</option>
</c:forEach>
</select><br/><br/>
旁边我想要一个字段,它将显示类似的东西
${userType.description}
对于下拉列表中的每个选项。
最好的方法是什么?
感谢任何花时间帮助我的人。
用JavaScript实现它。 我将在我的示例中使用 jQuery。
<select name="userType">
<c:forEach items="${userTypes}" var="userType">
<option value="${userType.userType}">${userType.userType}</option>
</c:forEach>
</select>
<%-- hidden descriptions waiting to be shown. --%>
<c:forEach items="${userTypes}" var="userType">
<div style="display:none" id="${userType.userType}" class="description">${userType.description}</div>
</c:forEach>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$('select[name=userType]').change(function() {
var userType = $(this).val()
$('.description').hide();
$('#' + userType).show();
});
</script>
要记住的几件事:
- 最初没有显示任何说明。如果需要,修复应该很简单。
- 我假设在我的示例中
userType
是独一无二的。 - 如果
description
或userType
包含 HTML,则它们可能会破坏您的标记。 考虑使用<c:out>
这更像是一个JavaScript问题。 好吧,你可以在服务器端做到这一点,但这将是矫枉过正。
我会使用 cleint side javascript 和 jquery,将 html/jsp 更改为
<select id="userType" name="userType">
<c:forEach items="${userTypes}" var="userType">
<option value=${userType.description}>${userType.userType}</option>
</c:forEach>
</select><span id="myDivNextSelectTag></span><br/><br/>
。和 jquery
$("#userType").change(function(){
$("#myDivNextSelectTag").html( $(this).value );
})
可能会有一些语法错误,但你应该明白 - 你也可以使用 data html attribute
而不是option value
。