后台傳進來一個List集合,存着某對象集合,將其顯示在下拉列表
一、HTML代碼
頁面有個下拉列表,如圖所示:
<td style="width:30%"> <select id="projectInfo"> <option value="-1">請選擇</option> </select> </td>
二、JS代碼
將每個對象的名字和對應ID都綁定在下拉列表,頁面顯示其名字,后台我們又能通過其id對其進行操作
function displayProject(obj){ var selector = document.getElementById("projectInfo"); for(var i=0;i<obj.length;i++){ var option = new Option(obj[i].projectName, obj[i].id); selector.options.add(option); } }
(obj:就是后台傳來的List對象集合)
new Option(text,value)
text:指定option對象的text屬性(即<option></option>之間的文字)
value:指定option對象的value屬性
三、Jquery獲取選中值
獲取選中的value
$('#projectInfo option:selected').val();
獲取選中的text
$('#projectInfo option:selected').text();
四、JavaScript獲取選中值
(1)獲得下拉列表
var projectInfo=document.getElementById("projectInfo");
(2)獲得選中項索引
var index = projectInfo.selectedIndex
(3)獲得選中項value或text
projectInfo.options[index].value;
projectInfo.options[index].text;