js添加select下默認(rèn)的option的value和text的方法

字號(hào):


    <pre name="code">
    jsp 中的下拉框標(biāo)簽:
    <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"意思是支持選擇多個(gè)。
    </pre><pre code_snippet_id="487056" snippet_file_name="blog_20141017_5_1612209" name="code">
    js中靈活創(chuàng)建select標(biāo)簽下的項(xiàng)的方式:
    代碼如下:
    <pre name="code">var oSelect = $("sjx");<span> </span>//sjx為html或jsp頁(yè)面上的select標(biāo)簽的id,如果使用Extjs的話,可以用EXT.getDom('sjx')獲取標(biāo)簽
    var oOption = document.createElement("OPTION");<span> </span>//js中創(chuàng)建select標(biāo)簽下的OPTION子標(biāo)簽
    oSelect.options.add(oOption);<span> </span>//將新建的OPTION子標(biāo)簽添加到select標(biāo)簽下
    oOption.value = "001";<span> </span>//內(nèi)容對(duì)應(yīng)的value值
    oOption.innerHTML ="小蘋果";<span> </span>//顯示的下拉框的內(nèi)容
    ...以此類推
    Note:js中的這種方式,在特定的場(chǎng)合是比較有用的,比如:這里請(qǐng)求不返回特定界面,也就是不刷新整個(gè)界面。而是采用Ajax方式的異步請(qǐng)求做一些局部的數(shù)據(jù)請(qǐng)求,那么這個(gè)時(shí)候下面strut2的方式,就會(huì)無(wú)效。
    復(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中定義一個(gè)List<Object>變量(以本例為例,命名為:sjxList),并設(shè)置set、get方法。
    通過(guò)一個(gè) HashMap 對(duì)象,添加內(nèi)容,比如:
    </pre>返回界面時(shí),將在界面的select下拉框中顯示“小蘋果”。
    <pre name="code">最簡(jiǎn)單的一種方式:
    直接在jsp頁(yè)面手動(dòng)添加select標(biāo)簽的OPTION項(xiàng)
    <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>