简体   繁体   English

Select 运行时下拉菜单中的默认值

[英]Select default value in a drop-down menu at run-time

Suppose we've a drop down menu like this假设我们有一个像这样的下拉菜单

<select name="op" >  
    <option value="1">A</option>  
    <option value="2">B</option>  
    <option value="3">C</option>  
</select>

Now, I need to specify that option with value "2" should be the default (I only know this when the page is being called so can't hardcode the default value) Am I correct that I need to get above code segment turned (at runtime) into something like现在,我需要指定值为“2”的选项应该是默认值(我只在调用页面时才知道这一点,所以不能硬编码默认值)我是否正确我需要转过代码段(在运行时)变成类似的东西

<select name="op" >  
    <option value="1">A</option>  
    <option selected value="2">B</option>  
    <option value="3">C</option>  
</select>

or is there a better/ easier way for which one won't need to iterate through each of the option value comparing and if a match is found adding the "selected" part in that line?还是有一种更好/更简单的方法,不需要遍历每个选项值比较并且如果找到匹配项,则在该行中添加“选定”部分?

No, that's it.不,就是这样。 But usually但通常

  1. Your list of values will be dynamic as well, and you'll have to iterate through it to generate your HTML options anyway您的值列表也将是动态的,无论如何您都必须遍历它以生成 HTML 选项
  2. You'll use some web framework which will provide JSP tags and/or UI components handling this for you.您将使用一些 web 框架,该框架将为您提供 JSP 标记和/或 UI 组件来处理此问题。 Your code will then look like this:您的代码将如下所示:

    <s:select name="op"> <s:options optionsCollection="${actionBean.theOptions}" value="id" label="name"/> </s:select>

you can set default value at runtime using javascript and JQuery like this:您可以使用 javascript 和 JQuery 在运行时设置默认值,如下所示:

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquerylatest.js"></script>
    <script>
        $(document).ready(function(){
            $('select[name=op] option[value=2]')attr('selected', 'selected');
        });
    </script>
</head>
<body>
    <select name="op">
        <option value="1">A</option>
        <option value="2">B</option>
        <option value="3">C</option>
    </select>
</body>
</html>

but one thing makes me wonder.但有一件事让我想知道。 if it is "written like static html code segment" as you stated why setting the default value at runtime?如果它是“像 static html 代码段一样编写”,如您所说,为什么在运行时设置默认值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM