使用$ .each的Jquery并没有得到变量的值

时间:2015-03-12 13:16:27

标签: jquery select add each options

我使用Jquery为select添加了一些选项,但是,选项并不总是相同的,因此,我使用一个名为materia的变量来获取previus选择的值以了解我应该选择哪些选项加。 我不知道我是否正确解释,这里有一些代码。

...

materia = $("#selMateria").val();

...

$.each(materia, function(val,text){
    $("#selGrupo").append(new Option(text,val));
});

我之前使用我可以获得的值的名称定义了变量

var name{
    opt : 'text'
}

问题在于,尽管我在var materia上得到了正确的值,但添加该选项的函数不起作用。

如果有人想看到整个代码:

的index.php

<div class="col-xs-6 col-centered form-group">
    <label for="facultad">Facultad</label>
    <select class="form-control" name="facultad" id="selFac" required>
        <option selected disabled hidden value="">---</option>
        <option value="ingenieria">Ingeniería</option>
        <option value="economia">Economía</option>
        <option value="derecho">Derecho</option>
    </select>
</div>
<div class="col-xs-6 col-centered form-group" id="divMateria">
    <label for="materia">Materia</label>
    <select class="form-control" name="materia" id="selMateria" required>
        <option selected disabled hidden value="">---</option>
    </select>
</div>
<div class="col-xs-12 col-centered form-group" id="divGrupo">
    <label for="grupo">Grupo</label>
    <select class="form-control" name="grupo" id="selGrupo" required>
        <option selected disabled hidden value="">---</option>
    </select>
</div>

在这里&#39; JQUERY FUNCTION

function addOpt(id, tipo, optDe) {
    removeAllSel(id);
    if (tipo == 'mat') {
        switch (optDe)
        {
            case 'ingenieria':
                $.each(matIng, function(val, text) {
                    $("#" + id).append(new Option(text, val));
                });
                break;
            case 'economia':
                $.each(matEco, function(val, text) {
                    $("#" + id).append(new Option(text, val));
                });
                break;
        }
    }
    else if (tipo == 'gru') {
        materia = $("#selMateria").val();
        $("#" + id).append(new Option($("#selMateria").val(), 'val'));
        $.each(materia, function(val, text) {
            $("#selGrupo").append(new Option(text, val));
        });
    }
    else {
        removeAllSel(id);
    }
}

非常感谢!

1 个答案:

答案 0 :(得分:0)

首先:

materia = $("#selMateria").val();
$("#" + id).append(new Option($("#selMateria").val(), 'val'));
$.each(materia, function(val, text) {
    $("#selGrupo").append(new Option(text, val));
});

在这种情况下,materia包含select的单个值。在这种情况下,$.each将仅针对该单个值进行迭代。我假设你想要类似的东西:

materia = $("#selMateria").val();
$("#" + id).append(new Option($("#selMateria").val(), 'val'));
$.each($("#selMateria"), function(val, text) {
    $("#selGrupo").append(new Option(text, val));
});