4

我有一个字符串eqArray的数组列表。

我需要在我的 JSP 中使用以下内容的下拉列表中显示它:

<% 

    for(int count=0;count<eqArray.size();count++){ %>
            <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
     <%} 
%>

我有一个 eqName 字符串,它是 eqArray 的一部分,默认情况下应该是选定的值。

我如何在不必检查并将第一个选项始终设置为 eqName 的情况下进行操作?

4

4 回答 4

5
<% for(int count=0; count<eqArray.size(); count++){ %>
    <option value="<%= eqArray.get(count) %>" <%= (eqArray.get(count).equals("eqName"))?"selected":"" %> ><%= eqArray.get(count) %></option>  
<%} %>
于 2012-04-12T08:47:40.307 回答
4

将数组中eqName元素的索引改为0,或者使用条件语句。

<% 
for(int count=0; count < eqArray.size(); count++){ %>
        <%if(eqArray.equals("eqName"){ %>           
            <option  selected="selected" value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
        <%} %> 
        <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
 <%} %>

但使用 JSTL taglibs 而不是使用 scriptlet。

于 2012-04-12T08:43:15.753 回答
3

您可以通过 JQuery 来完成,恕我直言,它更干净:

<select data-selected="${eqName}">
<% 
    for(int count=0;count<eqArray.size();count++){ %>
            <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
     <%} 
%>
</select>

在页面末尾:

<script type="text/javascript">
  $("select[data-selected]").each(function() {
      var selected = $(this).data("selected");
      $("select[data-selected='" + selected + "'] option[value='" + selected + "']").attr("selected", "selected");
  })
</script>

通过这种方式,您只需要在每个页面中包含 js。

顺便说一句,我建议您使用更具可读性的 JSTL 和 EL:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<select data-selected="${eqName}">
  <c:forEach items="${eqArray}" var="model">
    <option value="${model}">${model}</option>
  </c:forEach>
</select>
于 2012-04-12T09:01:46.973 回答
0

您可以通过两种方式实现这些

  • 通过使用jsp
  • " 选定="选定" >
  • 通过在选择框代码的末尾使用 Javascript

    document.getElementById('selectBoxID').value=""

    而不是 selectBoxID id 使用选择框 id

于 2012-04-17T14:07:28.770 回答