按字母顺序按自定义属性选择菜单中的选项

时间:2016-01-08 14:20:30

标签: javascript jquery sorting

这是我的HTMl选择菜单:

<select name="shipping_city" id="shipping-city-select" title="">
    <option value="">Изберете град</option>                     
    <option city_en="Aytos" value="1">гр. Айтос</option>
    <option city_en="Burgas" value="2">гр. Бургас</option>
    <option city_en="Asenovgrad" value="3">гр. Асеновград</option>
    <option city_en="Blagoevgrad" value="4">гр. Благоевград</option>
    <option city_en="Botevgrad" value="5">гр. Ботевград</option>
    <option city_en="Byala Rusensko" value="6">гр. Бяла, Русенско</option>
    <option city_en="Varna" value="7">гр. Варна</option>
    <option city_en="Veliko Tyrnovo" value="8">гр. Велико Търново</option>
    <option city_en="Vidin" value="9">гр. Видин</option>
    <option city_en="Vratsa" value="10">гр. Враца</option>
    <option city_en="Gabrovo" value="11">гр. Габрово</option>
    <option city_en="Gorna Oryahovitsa" value="12">гр. Горна Оряховица</option>
    <option city_en="Devnya" value="13">гр. Девня</option>
    <option city_en="Dryanovo" value="14">гр. Дряново</option>
    <option city_en="Dobrich" value="15">гр. Добрич</option>
    <option city_en="Dupnitsa" value="16">гр. Дупница</option>
    <option city_en="Ihtiman" value="17">гр. Ихтиман</option>
    <option city_en="Kazanlyk" value="18">гр. Казанлък</option>
    <option city_en="Karlovo" value="19">гр. Карлово</option>
    <option city_en="Karnobat" value="20">гр. Карнобат</option>
    <option city_en="Kostenets" value="21">гр. Костенец</option>
    <option city_en="Kyustendil" value="22">гр. Кюстендил</option>
    <option city_en="Kyrdzhali" value="23">гр. Кърджали</option>
    <option city_en="Lovech" value="24">гр. Ловеч</option>
    <option city_en="Lom" value="25">гр. Лом</option>
    <option city_en="Montana" value="26">гр. Монтана</option>
    <option city_en="Nova   Zagora" value="27">гр. Нова Загора</option>
    <option city_en="Pazardzhik" value="29">гр. Пазарджик</option>
    <option city_en="Pernik" value="30">гр. Перник</option>
    <option city_en="Petrich" value="31">гр. Петрич</option>
    <option city_en="Pleven" value="32">гр. Плевен</option>
    <option city_en="Plovdiv" value="33">гр. Пловдив</option>
    <option city_en="Razgrad" value="34">гр. Разград</option>
    <option city_en="Ruse" value="35">гр. Русе</option>
    <option city_en="Sandanski" value="36">гр. Сандански</option>
    <option city_en="Sevlievo" value="38">гр. Севлиево</option>
    <option city_en="Sliven" value="39">гр. Сливен</option>
    <option city_en="Sopot" value="40">гр. Сопот</option>
    <option city_en="Sofiya" value="41">гр. София</option>
    <option city_en="Stara Zagora" value="42">гр. Стара Загора</option>
    <option city_en="Troyan" value="43">гр. Троян</option>
    <option city_en="Tyrgovishte" value="44">гр. Търговище</option>
    <option city_en="Haskovo" value="45">гр. Хасково</option>
    <option city_en="Chirpan" value="46">гр. Чирпан</option>
    <option city_en="Shumen" value="47">гр. Шумен</option>
    <option city_en="Yambol" value="48">гр. Ямбол</option>
    <option city_en="Beloslav" value="50">гр. Белослав</option>
    <option city_en="Breznik" value="52">гр. Брезник</option>
    <option city_en="Velingrad" value="53">гр. Велинград</option>
    <option city_en="Elin Pelin" value="55">гр. Елин Пелин</option>
    <option city_en="Etropole" value="56">гр. Етрополе</option>
    <option city_en="Kalofer" value="59">гр. Калофер</option>
    <option city_en="Kozloduy" value="60">гр. Козлодуй</option>
    <option city_en="Lyaskovets" value="61">гр. Лясковец</option>
    <option city_en="Marten" value="62">гр. Мартен</option>
    <option city_en="Mezdra" value="63">гр. Мездра</option>
    <option city_en="Panagyurishte" value="64">гр. Панагюрище</option>
    <option city_en="Peshtera" value="65">гр. Пещера</option>
    <option city_en="Pomorie" value="67">гр. Поморие</option>
    <option city_en="Pravets" value="68">гр. Правец</option>
    <option city_en="Provadiya" value="69">гр. Провадия</option>
    <option city_en="Radomir" value="70">гр. Радомир</option>
    <option city_en="Svilengrad" value="72">гр. Свиленград</option>
    <option city_en="Svishtov" value="73">гр. Свищов</option>
    <option city_en="Senovo" value="74">гр. Сеново</option>
    <option city_en="Silistra" value="75">гр. Силистра</option>
    <option city_en="Smolyan" value="76">гр. Смолян</option>
    <option city_en="Tryavna" value="78">гр. Трявна</option>
    <option city_en="Apriltsi" value="82">гр. Априлци</option>
    <option city_en="Ardino" value="83">гр. Ардино</option>
    <option city_en="Balchik" value="86">гр. Балчик</option>
    <option city_en="Bankya" value="87">гр. Банкя</option>
    <option city_en="Bansko" value="88">гр. Банско</option>
    <option city_en="Batak" value="90">гр. Батак</option>
    <option city_en="Belene" value="91">гр. Белене</option>
    <option city_en="Belovo" value="93">гр. Белово</option>
    <option city_en="Bobov Dol" value="95">гр. Бобов Дол</option>
    <option city_en="Brezovo" value="102">гр. Брезово</option>
    <option city_en="Perushtitsa" value="103">гр. Перущица</option>
    <option city_en="Syedinenie" value="104">гр. Съединение</option>
    <option city_en="Rakovski" value="105">гр. Раковски</option>
    <option city_en="Pyrvomay" value="106">гр. Първомай</option>
    <option city_en="Sadovo" value="107">гр. Садово</option>
    <option city_en="Byala Slatina" value="108">гр. Бяла Слатина</option>
    <option city_en="Knezha" value="109">гр. Кнежа</option>
    <option city_en="Roman" value="110">гр. Роман</option>
    <option city_en="Septemvri" value="113">гр. Септември</option>
    <option city_en="Stamboliyski" value="114">гр. Стамболийски</option>
    <option city_en="Strelcha" value="115">гр. Стрелча</option>
    <option city_en="Rakitovo" value="116">гр. Ракитово</option>
    <option city_en="Rila" value="117">гр. Рила</option>
    <option city_en="Bratsigovo" value="118">гр. Брацигово</option>
    <option city_en="Tsarevo" value="119">гр. Царево</option>
    <option city_en="Sozopol" value="121">гр. Созопол</option>
    <option city_en="Slynchev Bryag" value="122">гр. Слънчев Бряг</option>
    <option city_en="Primorsko" value="124">гр. Приморско</option>
    <option city_en="Nesebyr" value="125">гр. Несебър</option>
    <option city_en="Kableshkovo" value="127">гр. Каблешково</option>
    <option city_en="Zavet" value="128">гр. Завет</option>
    <option city_en="Popovo" value="129">гр. Попово</option>
    <option city_en="Kubrat" value="130">гр. Кубрат</option>
    <option city_en="Isperih" value="131">гр. Исперих</option>
    <option city_en="Tsar Kaloyan" value="132">гр. Цар Калоян</option>
    <option city_en="Hisarya" value="133">гр. Хисаря</option>
    <option city_en="Klisura" value="134">гр. Клисура</option>
    <option city_en="Kirkovo" value="136">гр. Кирково</option>
    <option city_en="Krumovgrad" value="137">гр. Крумовград</option>
    <option city_en="Momchilgrad" value="138">гр. Момчилград</option>
    <option city_en="Vyrshets" value="139">гр. Вършец</option>
    <option city_en="Boychinovtsi" value="140">гр. Бойчиновци</option>
    <option city_en="Dolna Oryahovitsa" value="141">гр. Долна Оряховица</option>
    <option city_en="Strazhitsa" value="142">гр. Стражица</option>
    <option city_en="Elena" value="143">гр. Елена</option>
    <option city_en="Radnevo" value="145">гр. Раднево</option>
    <option city_en="Gylybovo" value="146">гр. Гълъбово</option>
    <option city_en="Dimitrovgrad" value="147">гр. Димитровград</option>
    <option city_en="Kresna" value="148">гр. Кресна</option>
    <option city_en="Harmanli" value="150">гр. Харманли</option>
    <option city_en="Lyubimets" value="151">гр. Любимец</option>
    <option city_en="Bozhurishte" value="153">гр. Божурище</option>
    <option city_en="Boboshevo" value="154">гр. Бобошево</option>
    <option city_en="Brusartsi" value="157">гр. Брусарци</option>
    <option city_en="Veliki Preslav" value="158">гр. Велики Преслав</option>
    <option city_en="Vylchedrym" value="161">гр. Вълчедръм</option>
    <option city_en="Vylchi Dol" value="162">гр. Вълчи Дол</option>
    <option city_en="General Toshevo" value="163">гр. Генерал Тошево</option>
    <option city_en="Gotse Delchev" value="168">гр. Гоце Делчев</option>
    <option city_en="Gurkovo" value="169">гр. Гурково</option>
    <option city_en="Debelets" value="171">гр. Дебелец</option>
    <option city_en="Dolni Dybnik" value="174">гр. Долни Дъбник</option>
    <option city_en="Dragoman" value="176">гр. Драгоман</option>
    <option city_en="Zlataritsa" value="180">гр. Златарица</option>
    <option city_en="Zlatograd" value="181">гр. Златоград</option>
    <option city_en="Kavarna" value="183">гр. Каварна</option>
    <option city_en="Kiten" value="188">гр. Китен</option>
    <option city_en="Kostinbrod" value="191">гр. Костинброд</option>
    <option city_en="Kotel" value="192">гр. Котел</option>
    <option city_en="Kocherinovo" value="193">гр. Кочериново</option>
    <option city_en="Kranevo" value="194">гр. Кранево</option>
    <option city_en="Kula" value="198">гр. Кула</option>
    <option city_en="Lukovit" value="201">гр. Луковит</option>
    <option city_en="Madan" value="202">гр. Мадан</option>
    <option city_en="Miziya" value="205">гр. Мизия</option>
    <option city_en="Myglizh" value="208">гр. Мъглиж</option>
    <option city_en="Nikopol" value="210">гр. Никопол</option>
    <option city_en="Novi Iskyr" value="212">гр. Нови Искър</option>
    <option city_en="Novi Pazar" value="213">гр. Нови Пазар</option>
    <option city_en="Omurtag" value="214">гр. Омуртаг</option>
    <option city_en="Oryahovo" value="215">гр. Оряхово</option>
    <option city_en="Pavel Banya" value="216">гр. Павел Баня</option>
    <option city_en="Pavlikeni" value="217">гр. Павликени</option>
    <option city_en="Pliska" value="220">гр. Плиска</option>
    <option city_en="Polski Trymbesh" value="222">гр. Полски Тръмбеш</option>
    <option city_en="Rudozem" value="229">гр. Рудозем</option>
    <option city_en="Samokov" value="230">гр. Самоков</option>
    <option city_en="Sveti Vlas" value="231">гр. Свети Влас</option>
    <option city_en="Svoge" value="233">гр. Своге</option>
    <option city_en="Simeonovgrad" value="234">гр. Симеоновград</option>
    <option city_en="Simitli" value="235">гр. Симитли</option>
    <option city_en="Slivnitsa" value="237">гр. Сливница</option>
    <option city_en="Sredets" value="240">гр. Средец</option>
    <option city_en="Suhindol" value="243">гр. Сухиндол</option>
    <option city_en="Tvyrditsa" value="244">гр. Твърдица</option>
    <option city_en="Tervel" value="245">гр. Тервел</option>
    <option city_en="Teteven" value="246">гр. Тетевен</option>
    <option city_en="Tutrakan" value="248">гр. Тутракан</option>
    <option city_en="Cherven  Bryag" value="249">гр. Червен Бряг</option>
    <option city_en="Chepelare" value="250">гр. Чепеларе</option>
    <option city_en="Shivachevo" value="252">гр. Шивачево</option>
    <option city_en="Shipka" value="253">гр. Шипка</option>
    <option city_en="Yablanitsa" value="254">гр. Ябланица</option>
    <option city_en="Dulovo" value="256">гр. Дулово</option>
    <option city_en="Devin" value="257">гр. Девин</option>
    <option city_en="Tryn" value="260">гр. Трън</option>
    <option city_en="Elhovo" value="263">гр. Елхово</option>
    <option city_en="Straldzha" value="276">гр. Стралджа</option>
    <option city_en="Pirdop" value="277">гр. Пирдоп</option>
    <option city_en="Levski" value="281">гр. Левски</option>
    <option city_en="Zlatitsa" value="286">гр. Златица</option>
    <option city_en="Belogradchik" value="288">гр. Белоградчик</option>
    <option city_en="Dolna Banya" value="294">гр. Долна Баня</option>
    <option city_en="Dospat" value="295">гр. Доспат</option>
    <option city_en="Krivodol" value="297">гр. Криводол</option>
    <option city_en="Alfatar" value="299">гр. Алфатар</option>
    <option city_en="Bulgaria" value="1033"> България</option>
    <option city_en="Borovo" value="1238">гр. Борово</option>
    <option city_en="Lyaskovets Sklad" value="1240">гр. Лясковец Склад</option>
    <option city_en="Loznitsa" value="1241">гр. Лозница</option>
    <option city_en="Kaspichan" value="1245">гр. Каспичан</option>
    <option city_en="Hadzhidimovo" value="1253">гр. Хаджидимово</option>
    <option city_en="Razlog" value="1270">гр. Разлог</option>
    <option city_en="Dobrinishte" value="1272">гр. Добринище</option>
    <option city_en="Belitsa" value="1277">гр. Белица</option>
    <option city_en="Yakoruda" value="1278">гр. Якоруда</option>
    <option city_en="Aksakovo" value="1284">гр. Аксаково</option>
    <option city_en="Shabla" value="1290">гр. Шабла</option>
    <option city_en="Obzor" value="1301">гр. Обзор</option>
    <option city_en="Dve Mogili" value="1382">гр. Две Могили</option>
    <option city_en="Banya" value="22454">гр. Баня</option>
    <option city_en="Bolyarovo" value="22668">гр. Болярово</option>
    <option city_en="Bregovo" value="22756">гр. Брегово</option>
    <option city_en="Bylgarovo" value="22859">гр. Българово</option>
    <option city_en="Byala Cherkva" value="22895">гр. Бяла Черква</option>
    <option city_en="Vetren" value="22976">гр. Ветрен</option>
    <option city_en="Vyrbitsa" value="23147">гр. Върбица</option>
    <option city_en="Glavinitsa" value="23260">гр. Главиница</option>
    <option city_en="Godech" value="23281">гр. Годеч</option>
    <option city_en="Gramada" value="23481">гр. Грамада</option>
    <option city_en="Gulyantsi" value="23516">гр. Гулянци</option>
    <option city_en="Dimovo" value="23631">гр. Димово</option>
    <option city_en="Dolna Mitropoliya" value="23735">гр. Долна Митрополия</option>
    <option city_en="Dunavtsi" value="23895">гр. Дунавци</option>
    <option city_en="Dylgopol" value="23942">гр. Дългопол</option>
    <option city_en="Zhergovets" value="24037">гр. Жерговец</option>
    <option city_en="Zemen" value="24138">гр. Земен</option>
    <option city_en="Iskyr" value="24274">гр. Искър</option>
    <option city_en="Kameno" value="24356">гр. Камено</option>
    <option city_en="Kaolinovo" value="24373">гр. Каолиново</option>
    <option city_en="Kermen" value="24432">гр. Кермен</option>
    <option city_en="Koynare" value="24528">гр. Койнаре</option>
    <option city_en="Koprivshtitsa" value="24584">гр. Копривщица</option>
    <option city_en="Kostandovo" value="24609">гр. Костандово</option>
    <option city_en="Kuklen" value="24745">гр. Куклен</option>
    <option city_en="Letnitsa" value="24837">гр. Летница</option>
    <option city_en="Lyki" value="24919">гр. Лъки</option>
    <option city_en="Madara" value="24960">гр. Мадара</option>
    <option city_en="Merichleri" value="25104">гр. Меричлери</option>
    <option city_en="Momin Prohod" value="25198">гр. Момин Проход</option>
    <option city_en="Nedelino" value="25286">гр. Неделино</option>
    <option city_en="Nikolaevo" value="25315">гр. Николаево</option>
    <option city_en="Opaka" value="25421">гр. Опака</option>
    <option city_en="Pordim" value="25744">гр. Пордим</option>
    <option city_en="Sapareva Banya" value="26144">гр. Сапарева Баня</option>
    <option city_en="Slivo Pole" value="26321">гр. Сливо Поле</option>
    <option city_en="Suvorovo" value="26562">гр. Суворово</option>
    <option city_en="Sungurlare" value="26566">гр. Сунгурларе</option>
    <option city_en="Syrnitsa" value="26600">гр. Сърница</option>
    <option city_en="Topolovgrad" value="26671">гр. Тополовград</option>
    <option city_en="Trystenik" value="26722">гр. Тръстеник</option>
    <option city_en="Ugyrchin" value="26770">гр. Угърчин</option>
    <option city_en="Tsarev Brod" value="26866">гр. Царев Брод</option>
    <option city_en="Chiprovtsi" value="27038">гр. Чипровци</option>
    <option city_en="Shtryklevo" value="27120">гр. Щръклево</option>
    <option city_en="Dolno Shivachevo" value="27229">гр. Долно Шивачево</option>
    <option city_en="Krayna" value="27312">гр. Крайна</option>
    <option city_en="Krichim" value="27338">гр. Кричим</option>
    <option city_en="Berkovitsa" value="27399">гр. Берковица</option>
    <option city_en="Panichishte" value="27465">гр. Паничище</option>
    <option city_en="AEC Kozloduj" value="27493"> АЕЦ Козлодуй</option>
    <option city_en="Lukoil Neftohim" value="27500">гр. Лукойл Нефтохим</option>
    <option city_en="Mobilen RC" value="27543">гр. Мобилен РЦ</option>
    <option city_en="izvoz" value="55950">гр. Извоз</option>
    <option city_en="Fürth" value="61003">гр. Фюрт</option>
    <option city_en="Mobilen RC (Rujinci)" value="61233">гр. Мобилен РЦ (Ружинци)</option>  
</select>

以下是我发现用于排序选项的内容,但它是根据值进行排序。

var options = $("#shipping-city-select option");                    // Collect options         
options.detach().sort(function(a,b) {               // Detach from select, then Sort
    var at = $(a).text();
    var bt = $(b).text();         
    return (at > bt)?1:((at < bt)?-1:0);            // Tell the sort function how to order
});
options.appendTo("#shipping-city-select");                          // Re-attach to select

如何使用jQuery按字母顺序按city_en属性重新排序此选择菜单中的所有选项?

提前致谢!

1 个答案:

答案 0 :(得分:4)

首先,您的HTML无效。您无法创建自己的属性。如果要使用元素存储自定义数据,请使用data-*属性,如下所示:

<option data-city-en="Aytos" value="1">гр. Айтос</option>

从那里你可以修改你的排序逻辑来读取data属性:

$("#shipping-city-select option[data-city-en]").sort(function(a, b) {
    var at = $(a).data('city-en');
    var bt = $(b).data('city-en');    
    return at > bt ? 1 : (at < bt) ? -1 : 0;
}).appendTo("#shipping-city-select");  

Example fiddle

请注意,在纠正顺序detach()之前,您无需append()元素。

另请注意,如果您使用localeCompare(),则可以直接对包含西里尔字符的文字进行排序:

$("#shipping-city-select option[data-city-en]").sort(function(a, b) {
    return $(a).text().localeCompare($(b).text());
}).appendTo("#shipping-city-select"); 

Example fiddle