var device_name = sreeni,murtuza,deepu,bharath,...... n th number
我需要根据逗号拆分此变量并将其放在下拉框中。
示例:
sreeni
murtuza
deepu
bhatah
请通过Javascript或Jquery提供解决方案
答案 0 :(得分:2)
使用普通JS,
var device_name = "sreeni , murtuza , deepu , bharath"
var list = device_name.split(/\s*,\s*/);
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
dd.innerHTML += '<option value="'+list[i]+'">'+list[i]+'</option>';
}
更多Hacky方式,
document
.getElementById("myDropDown2")
.innerHTML = device_name
.replace(
/\w+/g,
function(m){
return '<option value="'+m+'">'+m+'</option>'
}
)
.replace(/\s*,\s*/g,'');
答案 1 :(得分:1)
var myListOfWords = "apple,orange,bananna,cherries";
var list = myListOfWords.split(",");
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
var objOption = document.createElement("option");
objOption.text = list[i]
dd.add(objOption) ;
}
//和你的html中的某个地方
<select id="myDropDown"/>
以下是工作示例:dynamic drop down fiddle
答案 2 :(得分:1)
var strings = "sreeni,murtuza,deepu,bhatah";
var splitStrings = strings.split();
var selectObj = document.createElement("option");
for (var i in splitStrings) {
selectObj.options[selectObj.options.length] = new Option(splitStrings[i], splitStrings[i]);
}
document.getElementById("idOfElementToContainDropdown").appendChild(selectObj);
答案 3 :(得分:1)
var names = device_name.split(",");
var combo = document.getElementById("comboId");
//for i = 1 to length of names list {
var item = document.createElement("OPTION");
item.text=names[i];
combo.options.add(item);
}
希望这对你有所帮助。
答案 4 :(得分:1)
使用jQuery:
$('#myDropDown').empty();
$.each(device_name.split(","), function(iIndex, sElement) {
if ($.trim(sElement).length > 0) {
$('#myDropDown').append('<option>' + $.trim(sElement) + '</option>');
}
});
另见this example。