2016-05-16 43 views
-3

只有当我在on change事件中有代码时,列表才会被排序。我希望它在页面加载时排序。我尝试过使用onload,但没有成功。排序不排序javascript

此外,我试图让它,无论用户选择,该值是列表中的第一个。

作品...

myDropdown.onchange = function() { 
     $("#dropdown").append($("#dropdown option").sort(function(a, b) { 
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 
      })) 
     myTextBox.value = this.value; 
} 

不工作...

// var myDropdown = $('#dropdown'); 
// var opts_list = myDropdown.find('option'); 

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

// myDropdown.onload = function() { 
//  $('#dropdown option').sort(function(a,b) { return $(a).text() > $(b).text() ? 1 : -1; }); 
//  myDropdown.html('').append('#dropdown option'); 
// } 
// myDropdown.onload = function() { 
//  $("#dropdown").on($("#dropdown option").sort(function(a, b) { 
//   return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 
//  })) 
// } 
+0

'myDropdown'是一个jQuery对象。它没有'onload',但是你可以做'$(document).ready(function(){...});' – 4castle

+0

看看这个http://stackoverflow.com/questions/33757017 /下拉的JavaScript-的onload?RQ = 1 – aggaton

回答