jQuery在页面刷新时选择排序更改显示选项.什么'正在发生

jQuery select sort changing displayed option on page refresh. What's happening?

本文关键字:什么 选项 显示 刷新 选择 排序 jQuery      更新时间:2023-09-26

我使用以下jQuery对表单中的select元素进行排序:

$('select.select-sortable').each(function () {
    var options = $(this).children();
    var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
    arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
    options.each(function(i, o) {
      o.value = arr[i].v;
      $(o).text(arr[i].t);
    });
});

排序有效,但每次刷新页面时显示的值都会发生变化。无论还有多少个选项,它都会按顺序变化:第一个选项->第三个选项->第二个选项->第一个选项。

我已经将$(this).children(":first").attr("selected", true);添加到循环中,它将选择锁定到第一个选项,但我仍然不明白dsiplay为什么会更改,以及为什么会按这个顺序更改。有人有什么想法吗?

问题主要是因为没有捕获选项的selected属性。

$('select').each(function () {
    var options = $(this).children();
    var arr = options.map(function(_, o) {
      return { t: $(o).text(), v: o.value, s: $(o).attr('selected') };
    }).get();
    arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
    options.each(function(i, o) {
      o.value = arr[i].v;
      $(o).text(arr[i].t);
      if(arr[i].s!==undefined){
        $(o).attr('selected','selected');
      }
    });
});

这是因为浏览器缓存。它存储有关在按重新加载之前选择了哪个选项(具有什么值)的信息。如果您动态更改选项值,浏览器将在下次重新加载时反映这些更改,但您的脚本将立即再次修改这些值。它正在追赶你:)

Btw。您不必执行这样的构造:$(this).children(":first").attr("selected", true);简单的options[0].selected = true;放在options.each循环之后就足够了。

尝试以下代码,它会排序并选择您将传递的值。eq()

var arr = [],
$select = $("#ddsort"),
$options = $select.children();
$options.each(function(index, obj){
   arr.push($(this).val());
});
Array.sort(arr);
$select.empty();
$.each(arr,function(index, obj){
   $select.append("<option value="+obj+">"+obj+"</option>");   
});
$select.children().eq(2).attr("selected","selected");

请参阅此处的工作示例:http://jsfiddle.net/tFDNx/3/

我希望它能有所帮助。