1

我在同一个容器中有多个下拉列表,它们的第一项是“任何”选项。我正在寻找选择的单个选项的文本,或者如果选择“任何”(值 = 0),则获取该列表中选项的 REST OF 数组(但不是“任何”选项) . 序列化当然不起作用,因为我正在寻找某些列表中的未选择选项。

在我的简单测试中,以下内容可用于在一次选择中获取未选择的选项文本的文本:

var opts = $('select > option:not(:selected)').map(function() { return this.text; }).get();

但是当我翻译它以支持与我的容器中一样多的选择(一个未知数)时,我遇到了麻烦。map( .. ).get() / array concat 对我来说是最明显的方式,循环/推送似乎很乱(即使它只是在 jquery 中隐藏了相同的过程)

    var val = [];
    jQuery("select :selected", "#container").each(function () {
        if ($(this).val() == 0) { // "any"
            // _val.concat($(this).siblings().map(function() {return this.text; }).get()); // didn't work, even though siblings matches everything OTHER THAN the selected item
            _val.concat($('option:not(:selected)', $(this).parent()).map(function() { return this.text; }).get()); // didn't work either, even though this is all the options not selected mapped to an array
            //for (var i=0;i<$(this).siblings().length-1;i++) _val.push($(this).siblings().get(i).text()); // no; even though it is a <HTMLOptionElement>; ignore the potential bug in i if you spot it, it doesn't affect me!
        } else {
            _val.push(this.text); //$(this).text());
        }
    });
    _val.push(jQuery("input","#container").val());
    alert(_val.join(" ").toLowerCase()); // all my drop downs + my fields

像往常一样,这将是一些愚蠢的小东西,对我来说太明显了(而且这里已经很晚了)。

4

2 回答 2

0

这是我想出的,对我来说是一个解决方案:

    var _val = [];
    jQuery("select", "#container").each(function() {
        if ($(this).val() == 0) {
            jQuery.merge(_val, $(this).find('option:not(:selected)').map(function() { return this.text.toLowerCase(); }).get());
        } else {
            _val.push($(this).find('option:selected').map(function() { return this.text.toLowerCase(); }).get());
        }
    });
    _val.push(jQuery("input","#container").val().toLowerCase());
于 2012-10-19T02:50:46.407 回答
0

我已将您的脚本修改为:

var val = [];

jQuery("select", "#container").each(function() {
    if ($(this).val() == 0) {
        val.push($(this).find('option:not(:selected)').map(function() {
            return this.text;
        }).get());
    } else {
        val.push($(this).find('option:selected').map(function() {
            return this.text;
        }).get());
    }
});

alert(val.join(", ").toLowerCase()); 

请参阅此FIDDLE以检查它是否符合您的预期。

于 2012-10-18T08:54:02.403 回答