【问题标题】:Sorting a html select box but ignoring the select对 html 选择框进行排序但忽略选择
【发布时间】:2022-06-11 00:47:20
【问题描述】:

我有一个动态创建的 html 选择框,我需要按字母顺序排序,但忽略显示 Select...的占位符/选项...

我已经厌倦了 here 的以下内容,但意识到选择框没有 ID 只有名称

有什么想法吗?

<select style="width:250px" name="sortbyco">
    <option value="">Select2</option>
    <!--I would like to keep this at the top-->
    <option value="40934">Africa (CAF)</option>
    <option value="44624">Asia (AFC)</option>
    <option value="29521">Europe (UEFA)</option>
    <option value="43099">North &amp; Central America (CONCACAF)</option>
    <option value="38731">South America (CONMEBOL)</option>
    <option value="46617">Oceania (OFC)</option>
    <option value="40934">Africa (CAF2)</option>
</select>



$("#sortbyco").append($("#sortbyco option:gt(0)").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));

【问题讨论】:

  • 如果可能,请使用不同的 CSS 选择器 [name='sortbyco'],而不是 #sortbyco,或者简单地将 id='sortbyco' 添加到 &lt;select&gt; 标记
  • 这个列表是如何动态生成的?您能否在生成选择框之前对选项进行排序?
  • 不幸的是它来自一个插件,所以我们不能在它创建之前订购它!
  • 谢谢我试试选择器!

标签: javascript jquery


【解决方案1】:

这是一个没有 JQuery 的 sn-p。选择器现在有一个 id,以便在 css 选择器中使用。没有空选项的选项数组的副本被排序,并重新添加到选择器中。

// all options except the empty one
const opts = [...document.querySelectorAll(`#sortbyco option:not([value='']`)];
// copy options to a sorted array (note: use localeCompare to compare strings)
const sortedOpts = opts.sort( (a, b) => a.textContent.localeCompare(b.textContent) );
// remove the old options
opts.forEach(opt => opt.remove());
// add the sorted options to the selector
const selector = document.querySelector(`#sortbyco`);
sortedOpts.forEach( (opt, i) => selector.appendChild(opt));
<select style="width:250px" id="sortbyco">
    <option value="46617">Oceania (OFC)</option>
    <option value="43099">North &amp; Central America (CONCACAF)</option>
    <option value="40934">Africa (CAF)</option>
    <option value="44624">Asia (AFC)</option>
    <option value="29521">Europe (UEFA)</option>
    <option value="40934">Africa (CAF2)</option>
    <option value="38731">South America (CONMEBOL)</option>
    <option value="" selected>Select2</option>
</select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多