4

因此,如果您有一个 html 列表框,也称为多选,并且您想生成一个逗号分隔的字符串来列出该列表框中的所有值,您可以使用以下示例来做到这一点。list_to_string() js 函数是这里唯一重要的东西。您可以在http://josh.gourneau.com/sandbox/js/list_to_string.html使用此页面

<html>
<head>
    <script>
    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;
        }

    }
    </script>
</head>
<body>
    <form>
        <select name="list" id="list" size="3" multiple="multiple">
            <option value="India">India</option>
            <option value="US">US</option>
            <option value="Germany">Germany</option>
        </select>
        <input type="text" id="str" name="str" />
        <br /><br />
        <input type="button" id="chk" value="make a string!" name="chk" onclick="list_to_string();"/>
    </form>
</body>
</html>
4

3 回答 3

4

字符串连接在 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(",");
}
于 2009-02-13T07:20:15.167 回答
1

你可以使用 array.join(','); 从数组中创建一个逗号分隔的列表。

像这样,只有更好:

var list_to_string = function() {
    var opts = document.getElementById('list').options;
    var i = 0, len = opts.length, a = [];
    for (i; i<len; i++) {
        a.push(opts[i].value);
    }
    document.getElementById('str').value = a.join(',');
}
于 2009-02-13T07:19:20.787 回答
1

这也可以通过使用Request.Form(control.UniqueID)拉取已经存在于多选列表框的逗号分隔值来简单地完成。

于 2011-03-01T12:56:31.240 回答