1. 程式人生 > >實現select動態新增option並選中的多種方法

實現select動態新增option並選中的多種方法

 select動態新增option並選中,然後立刻把新增的option設為選中狀態

普通的javascript實現方法一:

var opt = document.createElement("OPTION");
opt.value = 6;
opt.text  = "分類名";
opt.selected ="selected";   
documtent.getElementById("cat").options.add(opt);

普通的javascript實現方法二:

// 建立一個 option

var newOption = new Option(str,incomeJson.catId,true

);

// 獲取到 select 物件

var diarySelect = document.getElementById('diarycat_id');

// 第一種給select新增option方法

diarySelect[diarySelect.length]=newOption;

// 第二種給select新增option方法

diarySelect.options.add(newOption);

// 讓新新增的option變成選中狀態

diarySelect.value=incomeJson.catId;

用jqueryp實現方法

$("#diarycat_id").append('<option value="'+incomeJson.catId+'" selected="selected">'+str+'</option>');