2

ユーザーが最初に国を選択してから、その国のオプションの郡リストをアクティブにできるようにする古い古い JavaScript コードがあります。読み込み時に、国のオプションは ANY と表示され、郡ラベルのオプションは最初に国を選択するように表示されるはずですが、そうではありません。ユーザーが最初に国を選択し、次に戻って [ANY] を選択した場合にのみ、[最初に郡を選択] 条件が表示されます。

jQueryは言うまでもなく、JavaScriptはまったく得意ではありません。既存の js を修正する方法、またはより優れた無駄のないコードで必要なものを達成する方法は?

よろしくお願いいたします。

<div>
  <label id="country">Country of birth:</label>
  <select name="country"  tabindex="7" onchange="populateCountiesDropdown(this[this.selectedIndex].value);">
    <option value="">Any</option>
    <option value="ENGLAND">England</option>
    <option value="IRELAND">Ireland</option>
    <option value="SCOTLAND">Scotland</option>
    <option value="WALES">Wales</option>
  </select>
  <script type="text/javascript">
        setSelect(document.main.country, '');
</script> 
</div>
<div>
  <label id="county">County of birth:</label>
  <select name="county"  tabindex="8">
  </select>
  <script type="text/javascript">
    populateCountiesDropdown(document.main.country.value);
    setSelect(document.main.county, "");
</script> 
</div>
<script type="text/javascript">
    var counties_dropdown = new Array(); 

        counties_dropdown["ENG"] = new Array("   |All counties in country" ,"BDF|Bedfordshire","BRK|Berkshire","BKM|Buckinghamshire","CAM|Cambridgeshire","CHI|Channel Islands","CHS|Cheshire","CON|Cornwall","CUL|Cumberland","DBY|Derbyshire","DEV|Devon","DOR|Dorset","DUR|Durham","ESS|Essex","GLS|Gloucestershire","HAM|Hampshire","HEF|Herefordshire","HRT|Hertfordshire","HUN|Huntingdonshire","IOM|Isle of Man","KEN|Kent","LAN|Lancashire","LEI|Leicestershire","LIN|Lincolnshire","LND|London","MDX|Middlesex","NFK|Norfolk","NTH|Northamptonshire","NBL|Northumberland","NTT|Nottinghamshire","OXF|Oxfordshire","RUT|Rutlandshire","SAL|Shropshire","SOM|Somerset","STS|Staffordshire","SFK|Suffolk","SRY|Surrey","SSX|Sussex","WAR|Warwickshire","WES|Westmorland","WIL|Wiltshire","WOR|Worcestershire","YKS|Yorkshire" );

        counties_dropdown["IRL"] = new Array("   |All counties in country" ,"ANT|Antrim","ARM|Armagh","CAR|Carlow","CAV|Cavan","CLA|Clare","COR|Cork","LDY|Derry (Londonderry)","DON|Donegal","DOW|Down","DUB|Dublin","FER|Fermanagh","GAL|Galway","KER|Kerry","KID|Kildare","KIK|Kilkenny","OFF|Kings (Offaly)","LET|Leitrim","LIM|Limerick","LOG|Longford","LOU|Louth","MAY|Mayo","MEA|Meath","MOG|Monaghan","NAI|Nairnshire","LEX|Queens (Laois)","ROS|Roscommon","SLI|Sligo","TIP|Tipperary","TYR|Tyrone","WAT|Waterford","WEM|Westmeath","WEX|Wexford","WIC|Wicklow" );

        counties_dropdown["SCT"] = new Array("   |All counties in country" ,"ABD|Aberdeenshire","ARL|Argyllshire","AYR|Ayrshire","BAN|Banffshire","BEW|Berwickshire","BUT|Buteshire","CAI|Caithness","CLK|Clackmannanshire","DFS|Dumfriesshire","DNB|Dunbartonshire","FIF|Fife","ANS|Forfarshire (Angus)","ELN|Haddingtonshire (East Lothian)","INV|Invernessshire","KCD|Kincardineshire","KRS|Kinrossshire","KKD|Kirkcudbrightshire","LKS|Lanarkshire","WLN|Linlithgowshire (West Lothian)","MLN|Midlothian","MOR|Morayshire","PEE|Peeblesshire","PER|Perthshire","RFW|Renfrewshire","ROC|Ross and Cromarty","ROX|Roxburghshire","SEL|Selkirkshire","SHI|Shetland Islands","STI|Stirlingshire","SUT|Sutherland","WIG|Wigtownshire" );

        counties_dropdown["WLS"] = new Array("   |All counties in country" ,"AGY|Anglesey","BRE|Brecknockshire","CAE|Caernarvonshire","CGN|Cardiganshire","CMN|Carmarthenshire","DEN|Denbighshire","FLN|Flintshire","GLA|Glamorganshire","MER|Merionethshire","MON|Monmouthshire","MGY|Montgomeryshire","PEM|Pembrokeshire","RAD|Radnorshire" );

    function populateCountiesDropdown(formObj, country) {
        formObj.county.options.length = 0;
        if(country == "") {
            formObj.county.options[0] = new Option('Choose a country first', '');
            return;
        }
        for(i = 0; i < counties_dropdown[country].length; i++) {
            var option = new Option(counties_dropdown[country][i].substr(counties_dropdown[country][i].indexOf('|')+1), 
                                    counties_dropdown[country][i].substr(0,counties_dropdown[country][i].indexOf('|')));
            formObj.county.options[i] = option;
        }
        formObj.county.options[0].value = '';
    }
</script> 
4

3 に答える 3

1

コメントで提案されているように、jQuery を使用すると、このコードが読みやすくなります。しかし、私の意見では、あなたができる最善の最適化は郡のデータ構造にあります。これを、アイテムがパイプ文字で区切られた配列ではなく、マップにしてから分割する必要があります。あれは:

  var counties = {
    'ENGLAND': {
      'BDF': 'Bedfordshire',
      'BRK': 'Berkshire',
      ...
    },
    'IRELAND': {
      'ANT': 'Antrim',
      'ARM': 'Armagh',
      ...
    },
    'SCOTLAND': {
      'ABD': 'Aberdeenshire',
      'ARL': 'Argyllshire',
      ...
    },
    'WALES': {
      'AGY': 'Anglesey',
      'BRE': 'Brecknockshire',
      ...
    }
  };

国選択の値からのキーを使用してこれを駆動し、郡のドロップダウンに入力できるようになりました。.change()国の変化を監視するには、jQuery の関数を使用できます。

jQuery APIのドキュメントを読んで実験することをお勧めします。SO ユーザーに質問に答えてもらっても、あまり進歩しません。ただし、これが私の実用的なソリューションです: http://jsfiddle.net/pfYEb/

于 2012-11-30T15:25:23.023 に答える
1

ほら、コメントもいくつか追加しました。動作確認済み。

<script type="text/javascript">
    var counties_dropdown = new Array();
    counties_dropdown["ENG"] = new Array("   |All counties in country", "BDF|Bedfordshire", "BRK|Berkshire", "BKM|Buckinghamshire", "CAM|Cambridgeshire", "CHI|Channel Islands", "CHS|Cheshire", "CON|Cornwall", "CUL|Cumberland", "DBY|Derbyshire", "DEV|Devon", "DOR|Dorset", "DUR|Durham", "ESS|Essex", "GLS|Gloucestershire", "HAM|Hampshire", "HEF|Herefordshire", "HRT|Hertfordshire", "HUN|Huntingdonshire", "IOM|Isle of Man", "KEN|Kent", "LAN|Lancashire", "LEI|Leicestershire", "LIN|Lincolnshire", "LND|London", "MDX|Middlesex", "NFK|Norfolk", "NTH|Northamptonshire", "NBL|Northumberland", "NTT|Nottinghamshire", "OXF|Oxfordshire", "RUT|Rutlandshire", "SAL|Shropshire", "SOM|Somerset", "STS|Staffordshire", "SFK|Suffolk", "SRY|Surrey", "SSX|Sussex", "WAR|Warwickshire", "WES|Westmorland", "WIL|Wiltshire", "WOR|Worcestershire", "YKS|Yorkshire");
    counties_dropdown["IRL"] = new Array("   |All counties in country", "ANT|Antrim", "ARM|Armagh", "CAR|Carlow", "CAV|Cavan", "CLA|Clare", "COR|Cork", "LDY|Derry (Londonderry)", "DON|Donegal", "DOW|Down", "DUB|Dublin", "FER|Fermanagh", "GAL|Galway", "KER|Kerry", "KID|Kildare", "KIK|Kilkenny", "OFF|Kings (Offaly)", "LET|Leitrim", "LIM|Limerick", "LOG|Longford", "LOU|Louth", "MAY|Mayo", "MEA|Meath", "MOG|Monaghan", "NAI|Nairnshire", "LEX|Queens (Laois)", "ROS|Roscommon", "SLI|Sligo", "TIP|Tipperary", "TYR|Tyrone", "WAT|Waterford", "WEM|Westmeath", "WEX|Wexford", "WIC|Wicklow");
    counties_dropdown["SCT"] = new Array("   |All counties in country", "ABD|Aberdeenshire", "ARL|Argyllshire", "AYR|Ayrshire", "BAN|Banffshire", "BEW|Berwickshire", "BUT|Buteshire", "CAI|Caithness", "CLK|Clackmannanshire", "DFS|Dumfriesshire", "DNB|Dunbartonshire", "FIF|Fife", "ANS|Forfarshire (Angus)", "ELN|Haddingtonshire (East Lothian)", "INV|Invernessshire", "KCD|Kincardineshire", "KRS|Kinrossshire", "KKD|Kirkcudbrightshire", "LKS|Lanarkshire", "WLN|Linlithgowshire (West Lothian)", "MLN|Midlothian", "MOR|Morayshire", "PEE|Peeblesshire", "PER|Perthshire", "RFW|Renfrewshire", "ROC|Ross and Cromarty", "ROX|Roxburghshire", "SEL|Selkirkshire", "SHI|Shetland Islands", "STI|Stirlingshire", "SUT|Sutherland", "WIG|Wigtownshire");
    counties_dropdown["WLS"] = new Array("   |All counties in country", "AGY|Anglesey", "BRE|Brecknockshire", "CAE|Caernarvonshire", "CGN|Cardiganshire", "CMN|Carmarthenshire", "DEN|Denbighshire", "FLN|Flintshire", "GLA|Glamorganshire", "MER|Merionethshire", "MON|Monmouthshire", "MGY|Montgomeryshire", "PEM|Pembrokeshire", "RAD|Radnorshire");

    function populateCountiesDropdown(country) {
        // get the html element
        var select = document.getElementById("county");

        // remove all options from select
        select.options.length = 0;

        if (country == "") {
            select.options[0] = new Option('Choose a country first', '');
            return;
        }
        for (i = 0; i < counties_dropdown[country].length; i++) {

            // split the element of county array
            // for example after split county array will contain
            // county[0] = 'BDF',
            // county[1] = 'Bedfordshire',
            var county = counties_dropdown[country][i].split('|');

            // add a new option to the select by inserting it to the index of length
            // note that length is zero based, so current length would be the index that you need to
            // add the new option.
            select.options[select.options.length] = new Option(county[1], county[0]);
        }
    }
</script>
<div>
    <label for="country">Country of birth:</label>
    <select id="country" name="country" tabindex="7" onchange="populateCountiesDropdown(this[this.selectedIndex].value);">
        <option value="" selected="selected">Any</option>
        <option value="ENG">England</option>
        <option value="IRL">Ireland</option>
        <option value="SCT">Scotland</option>
        <option value="WLS">Wales</option>
    </select>
</div>
<div>
    <label for="county">County of birth:</label>
    <select id="county">
        <option value=""> Choose a country first</option>
    </select>
</div>
于 2012-11-30T15:31:24.397 に答える
1

これにはさまざまな方法がありますが、簡単な方法の 1 つは、HTML で初期状態をハード コードし、必要に応じて Javascript で上書きすることです。

<select name="county"  tabindex="8">
  <option>Choose a country first</option>
</select>
于 2012-11-30T14:56:35.373 に答える