js添加select下默認的option的value和text的方法

字號:


    <pre name="code">
    jsp 中的下拉框標簽:
    <s:select name="sjx" id="sjx" list="sjxList" listKey="BM" listValue="MC" size="20" cssStyle="width:100%;height:70px; border:0" multiple="true"></s:select>
    代碼如下:
    <pre name="code">
    multiple="true"意思是支持選擇多個。
    </pre><pre code_snippet_id="487056" snippet_file_name="blog_20141017_5_1612209" name="code">
    js中靈活創(chuàng)建select標簽下的項的方式:
    代碼如下:
    <pre name="code">var oSelect = $("sjx");<span> </span>//sjx為html或jsp頁面上的select標簽的id,如果使用Extjs的話,可以用EXT.getDom('sjx')獲取標簽
    var oOption = document.createElement("OPTION");<span> </span>//js中創(chuàng)建select標簽下的OPTION子標簽
    oSelect.options.add(oOption);<span> </span>//將新建的OPTION子標簽添加到select標簽下
    oOption.value = "001";<span> </span>//內(nèi)容對應(yīng)的value值
    oOption.innerHTML ="小蘋果";<span> </span>//顯示的下拉框的內(nèi)容
    ...以此類推
    Note:js中的這種方式,在特定的場合是比較有用的,比如:這里請求不返回特定界面,也就是不刷新整個界面。而是采用Ajax方式的異步請求做一些局部的數(shù)據(jù)請求,那么這個時候下面strut2的方式,就會無效。
    復(fù)制代碼 代碼如下:
    <pre name="code"><pre name="code">for(...){
    HashMap<String,Object> map = new HashMap<String,Objcet>();
    map.put("BM","001");
    map.put("MC","小蘋果");
    sjxList.add(map);
    }
    另外一種方式,也是非常常用的:利用struts2的特性,在Action中定義一個List<Object>變量(以本例為例,命名為:sjxList),并設(shè)置set、get方法。
    通過一個 HashMap 對象,添加內(nèi)容,比如:
    </pre>返回界面時,將在界面的select下拉框中顯示“小蘋果”。
    <pre name="code">最簡單的一種方式:
    直接在jsp頁面手動添加select標簽的OPTION項
    <html>
    <body>
    <form>
    <select id="cars" name="cars">
    <option value="volvo">Volvo</option>
    <option value="binli">Binli</option>
    <option value="mazda" selected="selected">Mazda</option>
    <option value="audi">Audi</option>
    </select>
    </form>
    </body>
    </html>