1. 程式人生 > >js 對 select 中的 option 進行中文排序問題

js 對 select 中的 option 進行中文排序問題

從資料庫中讀取出 select 列表的 option 值是按照資料庫中的順序進行排列的,有時需要對 optiion 的中文按照字母序進行排序,這時需要注意的問題是  option 的 text 值 和 value 值要同時排序。這樣提交 form 表單將資料提交到資料庫時就能按照 正確的 value 值進行插入資料了。

下面是一個寫好的  sortOptions(oSel) 對 option進行排序的函式, oSel 為 select 的名字。

var select = document.getElementById('select') ;

 
select_root.options.length = 0 ;		// 長度清零
			
// 新增 " --市-- "
var cityOption = document.createElement("option") ;
cityOption.innerText = "--市--" ;		
select_root.appendChild(cityOption) ;
			
for(var i = 0; i < xSel.length; i ++) {
<span style="white-space:pre">	</span>var xValue = xSel[i].childNodes[0].firstChild.nodeValue;  
	var xText = xSel[i].childNodes[1].firstChild.nodeValue ;
				
	var option = new Option(xText, xValue) ;
				
	try{
		select_root.add(option) ;
	}catch(e){}
}
			
// 排序
sortOptions(select_root) ;

function sortOptions(oSel) {
	var ln = oSel.options.length ;
	var txt = new Array() ;
	var val = new Array() ;
	
	for(var i = 0; i < ln; i ++) {
		txt[i] = oSel.options[i].text ;
		val[i] = oSel.options[i].value ;
	}
	
	toSort(txt, val) ;
	
	oSel.options.length = 0 ;
	
	for(var i = 0; i < txt.length; i ++) {
		oSel.add(new Option(txt[i], val[i])) ;
	}
	
}

function toSort(txt, val) {
	var j, k, temp ;
	for(var i = 1; i < txt.length-1; i ++) {
		k = i ;
		for(var j = i+1; j < txt.length; j ++ ) 
			if( txt[k].localeCompare(txt[j]) == 1 ){
				k = j ;
			}
		temp = txt[k] ;
		txt[k] = txt[i] ;
		txt[i] = temp ;
		
		temp = val[k] ;
		val[k] = val[i] ;
		val[i] = temp ;
		
	}
}