因此,如果您有一个html列表框,也称为多选,并且您希望生成一个逗号分隔的字符串,列出该列表框中的所有值,您可以使用以下示例执行此操作. list_to_string()js函数是这里唯一重要的事情.你可以在http://josh.gourneau.com/sandbox/js/list_to_string.html玩这个页面
function list_to_string()
{
var list = document.getElementById('list');
var chkBox = document.getElementById('chk');
var str = document.getElementById('str');
textstring = "";
for(var i = 0; i < list.options.length; ++i){
comma = ",";
if (i == (list.options.length)-1){
comma = "";
}
textstring = textstring + list[i].value + comma;
str.value = textstring;
}
}
India
US
Germany
解决方法:
IE上的字符串连接非常慢,请使用数组:
function listBoxToString(listBox,all) {
if (typeof listBox === "string") {
listBox = document.getElementById(listBox);
}
if (!(listBox || listBox.options)) {
throw Error("No options");
}
var options=[],opt;
for (var i=0, l=listBox.options.length; i < l; ++i) {
opt = listBox.options[i];
if (all || opt.selected ) {
options.push(opt.value);
}
}
return options.join(",");
}
标签:javascript,textbox,listbox,string,html
来源: https://codeday.me/bug/20190607/1193157.html
JS列表框转逗号分隔值
本文介绍了一个实用的JavaScript函数,用于将HTML列表框中的所有选定值转换为逗号分隔的字符串。提供了两种实现方法,一种直接拼接字符串,另一种使用数组和join方法,后者在Internet Explorer上性能更优。
1509

被折叠的 条评论
为什么被折叠?



