jQuery每次循环一次

时间:2014-12-17 09:18:03

标签: jquery html

<script type="text/javascript">
    $(document).ready(function () {
        var country = ["United States", "Canada", "Australia", "United Kingdom"];
        var state = {
            "United States": "Alaska",
            "United States" : "Alabama"
        };
        $(this).click(function () {
            if ($.inArray($(this).val(), country)) {
                $.each(state, function (key, val) {
                    if ($("#country").val() == key) {
                        $("#state").append("<option value=" + val + ">" + val + "</option>");
                    }
                });
            }
        });
    });
</script>

基本上我要做的是,我有一个针对国家的多选,我想根据用户点击国家/地区来填充“#state”,现在它只显示第一个项目“阿拉斯加“在多重选择下。

不完全确定我做错了什么。

3 个答案:

答案 0 :(得分:5)

你做不到:

var state = {
    "United States" : "Alaska",
    "United States" : "Alabama"
};

对象中的键必须是唯一的。您的第二个"United States"密钥会覆盖第一个"United States"密钥,而您的对象只是

var state = {
    "United States" : "Alabama"
};

相反,您需要存储一个将国家/地区映射到状态的对象:

var state = {
    "United States" : ["Alaska", "Alabama"],
    "United Kingdom" : ["Scotland", "England"] // "states" in the UK?
};

...然后相应地更改您的点击处理程序:

$(this).click(function () {
    if ($.inArray($(this).val(), country)) {
        $.each(state, function (key, val) {
            if ($("#country").val() == key) {
                $.each(val, function (i, name) { 
                    $("#state").append("<option value=" + name + ">" + name + "</option>");
                });
            }
        });
    }
});

注意

  1. 您的$(this).click()选择器可能有误。它应该是ID或类选择器(例如$('#your_id')$('.your-class'))。

  2. 您可能希望清空 $('#state')选择,然后才能追加它。为此,请在点击处理程序中添加$(this).children().remove()(但在循环之外)。

  3. 我不确定为什么要保留一系列国家/地区名称,以及将国家/地区名称映射到州的对象;取消使用country,只需使用state的密钥即可获取您的国家/地区。

  4. 请记住,多选的$().val()会返回结果数组,而不是单个值。

  5. 考虑到所有这些注释,并考虑到一些错误。整理,这是我提出的代码:

    $(document).ready(function () {
        var countries = {
            "United States": ["Alaska", "Alabama"],
            "United Kingdom": ["Scotland", "England"] // "states" in the UK?
        };
    
        // SETUP: Ignore this bit.
        Object.keys(countries).forEach(function (val) {
           $('#multiselect').append('<option value="' + val + '">' + val + '</option>');
        });
        // END SETUP.
    
        $('#multiselect').change(function () {
            var vals = $(this).val();
            var states = $('#state');
            
            states.children().remove();
            
            jQuery.each(vals, function (i, name) {          
                var country = countries[name];
                
                jQuery.each(country, function (i, val) {
                    states.append('<option value="' + val + '">' + val + '</option>');
                });
            });
        });    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <select multiple="multiple" id="multiselect"></select>
    <select multiple="multiple" id="state"></select>

    在此处查看:http://jsfiddle.net/6dnbgf24/1/

答案 1 :(得分:2)

使用相同的键设置多个值是不可能的,您必须以这种方式将值包装到数组中:

var state = {
"United States" : ["Alaska", "Alabama"]
};

然后相应地更新您的代码:

$.each(state, function(key, val){           
    for( var i in val){
        $("#state").append("<option value="+val[i]+">"+val[i]+"</option>");
        }
    });

以上代码尚未经过测试,可能包含不匹配的括号。

答案 2 :(得分:0)

你可以这样做

<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var myJson = {
    "country": [
        {
            "name": "United States",
            "id": "usa",
            "states": [
                {
                    "name": "State 1 USA",
                    "id": "usaState1",
                    "cid": "usa",
                    "cities": [
                        {
                            "name": "City 1",
                            "id": "usaState1City1",
                            "area": "12345 sqkm"
                        },
                        {
                            "name": "City 2",
                            "id": "usaState1City2",
                            "area": "12345 sqkm"
                        }
                    ]
                },
                {
                    "name": "State 2 USA",
                    "id": "usaState2",
                    "cid": "usa",
                    "cities": [
                        {
                            "name": "City 3",
                            "id": "usaState2City3",
                            "area": "12345 sqkm"
                        },
                        {
                            "name": "City 4",
                            "id": "usaState2City4",
                            "area": "12345 sqkm"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Australia",
            "id": "aus",
            "states": [
                {
                    "name": "State 1 Australia",
                    "id": "ausState1",
                    "cid": "aus",
                    "cities": [
                        {
                            "name": "City 5",
                            "id": "ausState1City5",
                            "area": "12345 sqkm"
                        },
                        {
                            "name": "City 6",
                            "id": "ausState1City6",
                            "area": "12345 sqkm"
                        }
                    ]
                },
                {
                    "name": "State 2 Australia",
                    "id": "ausState2",
                    "cid": "aus",
                    "cities": [
                        {
                            "name": "City 7",
                            "id": "ausState2City7",
                            "area": "12345 sqkm"
                        },
                        {
                            "name": "City 8",
                            "id": "ausState2City8",
                            "area": "12345 sqkm"
                        }
                    ]
                }
            ]
        }
    ]
}


$(document).ready(function(){
$.each(myJson.country, function (index, value) {
    //alert(value.name);
    $("#country").append('<option value="'+value.id+'">'+value.name+'</option>');
});

$("#country").click(function () { 
      var countryId = $(this).val();

        if(cntryId !=''){
           $('#selectedvalue').val($(this).val());
        }else{
           $('#selectedvalue').val($(this).val());
        }
      var cntryId   =$('#selectedvalue').val();
      var exist     = cntryId.indexOf(','); 
      if(parseInt(exist) > 0){
           $("#state").html('');
          var array     = cntryId.split(",");
          $.each(array,function(i){  
                selectedId =array[i];               
                getState(selectedId);   
            });
        }else{
            $("#state").html('');
            getState(cntryId)
        }   

});

});

function getState(countryId){
     $.each(myJson.country, function (index, value) {
                    var state =value.states;

                    $.each(state, function (indexState, valueState) {
                            //alert(countryId+"=="+valueState.cid);
                            if(countryId==valueState.cid){
                                $("#state").append('<option value="'+value.indexState+'">'+valueState.name+'</option>');
                            }
                    });
    });

}

</script>

<form id="dropdowns" action="index.html">

            <label>Country:</label>
                <select id="country" name="country" multiple>
                    <option value="000">-Select Country-</option>
                </select>

            <br />

            <label>State:</label>
                <select id="state" name="network">
                    <option value="000">-Select State-</option>
                </select>

            <br />

            <label>City:</label>
                <select id="model" name="model">
                    <option value="000">-Select City-</option>
                </select>

            <br />
                <input type="hidden" id="selectedvalue" value="">
        </form>
</body>
</html>