问题描述
我正在为我的Web应用程序进行配置,请尝试将其呈现到网页上.下面是我的代码的一部分.我想将选项选择为config [0] .volume.因此,如果config [0] .volume为'50',则所选选项将为'50'.这些代码运行良好.但是我想知道. 如何缩短此代码?"我的代码太冗长了.
I'm making a configuration for my web application, try to rendering it to web page. Below is part of my code. I want to the option selected to the config[0].volume has. So, if config[0].volume is '50', The selected option will be '50'. The codes are working well. But I wondered. 'How can I shorten this code?' So verbose with my code.
<select id="volume">
<option value="1" <%= config[0].volume == '1' ? 'selected' : ''%>>1</option>
<option value="5" <%= config[0].volume == '5' ? 'selected' : '' %>>5</option>
<option value="10" <%= config[0].volume == '10' ? 'selected' : '' %>>10</option>
<option value="50" <%= config[0].volume == '50' ? 'selected' : '' %>>50</option>
<option value="75" <%= config[0].volume == '75' ? 'selected' : '' %>>75</option>
<option value="100" <%= config[0].volume == '100' ? 'selected' : '' %>>100</option>
</select>
我认为大约2个小时,但是什么也没发生.也许我必须使用jquery或javascript,并为其添加属性
I think about 2 hours, but nothing comes up. Maybe I have to use jquery or javascript , and add attribute to has it,
attr('selected')... ?
我不知道,你能帮我吗?.
I have no idea, Could you help me..?
推荐答案
您可以根据选项值将其放入循环中.
You can put it in a loop based on the option values.
<select id="volume">
<%
var options = [ "1", "5", "10", "50", "75", "100" ];
for ( var i = 0; i < options.length; i++ )
{
var selected = ( config[0].volume == i ) ? "selected" : "";
%><option value="<%=options[ i ] %>" <%=selected %>><%=i %></option><%
}
%>
</select>
这篇关于EJS的HTML选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!