2008-04-27

不能選擇的 option

在<select>裡頭,偶爾會有單純解說、不能選擇的<option>標籤。標準的做法如下:
<option disabled="disabled">
但在 IE7 以下都不支援。以下是網路上領領有名的 "select-option-disabled-emulation.js" 解法,為了減少 Firefox 等支援標準的瀏覽器的載入時間,我多加了一行。

function setDisabledSelect() {
if(navigator.appName != 'Microsoft Internet Explorer')
return; // only for bogus IE
if(document.getElementsByTagName) {
var s = document.getElementsByTagName("select");
if (s.length > 0) {
window.select_current = new Array();
for (var i=0, select; select = s[i]; i++) {
select.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
select.onchange = function(){ restore(this); }
emulate(select);
}
}
}
}

function restore(e) {
if (e.options[e.selectedIndex].disabled) {
e.selectedIndex = window.select_current[e.id];
}
}

function emulate(e) {
for (var i=0, option; option = e.options[i]; i++) {
if (option.disabled) {
option.style.color = "graytext";
} else {
option.style.color = "menutext";
}
}
}

2008-04-13

用 PHP 排序含有 1,2,3,A,B,C,甲乙丙 的陣列

以一維陣列舉例。因為裡面用的是 array_multisort(), 所以從資料庫裡抓出來的也可以一次排序。這種做法只是可行而已,具體的限制請看程式碼...

// sort data records according to natural order and Chinese order
function zhNatSort(&$data) {
$key1 = array();
$zh = array('甲','乙','丙','丁','戊','己','庚','辛','壬','癸');
foreach($data as $l => $v) {
if(ereg('^[0-9]+$', $v))
$v = sprintf('%09d', $v);
elseif(in_array($v, $zh))
$v = sprintf('zzzz%02d%s', array_search($v, $zh), $v);
$key1[$l] = $v;
}
array_multisort($key1, SORT_ASC, $data);
}

測試:

$t = array('1','11','5','15','51','4','7','A','E','C','B','丁','甲','辛','己');
zhNatSort($t);
print_r($t);