It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center




8年前关闭。




因此,如果您有一个 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>

最佳答案

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 - 使用 Javascript 从 HTML 列表框(多选)中的项目生成逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/544936/

10-12 07:27