尝试设置所选属性,代码以两个 <option> 元素结尾

Trying to set selected attribute, code ends up with two <option> elements

我正在尝试在下拉列表中设置 selected 值。所以我通过比较 select 选项的索引来做到这一点,如下所示,

<c:set var="questionids" value="Select Question,Employed?,Name?,Age (40+),Drinker?,Tobacco?,Smoker?" scope="application"/>
<select name="questionids" id="questionids" >
    <c:forEach items="${fn:split(questionids, ',')}" var="questionids" varStatus="loop">
        <c:if test="${healthWorkerQuestions == loop.index}" >
            <option value="${loop.index}" selected>${questionids}</option>
        </c:if>
        <c:if test="${healthWorkerQuestions != questionids}" >
            <option value="${loop.index}">${questionids}</option>
        </c:if>
    </c:forEach>
</select>

问题: 使用上面的代码,它正在比较索引和 selected 匹配的索引。与此同时,它再次插入选项。

我不想再次插入该选项。我只需要 select 匹配的索引,不需要再次插入。

那么我怎样才能设置匹配的索引而不是再次插入?

这是因为您添加了两次选项元素。您希望仅在 selected 属性上具有 <c:if test="${healthWorkerQuestions == loop.index}" 此条件。不在整个 option 标签

<c:set var="questionids" value="Select Question,Employed?,Name?,Age (40+),Drinker?,Tobacco?,Smoker?" scope="application"/>
       <select name="questionids" id="questionids" >
            <c:forEach items="${fn:split(questionids, ',')}" var="questionids" varStatus="loop">
                   <c:if test="${healthWorkerQuestions != questionids}" >            
                      <option value="${loop.index}" 
                       <c:if test="${healthWorkerQuestions == loop.index}" >selected</c:if>
                       >${questionids}</option>
                    </c:if>
           </c:forEach>
    </select>