標籤:
公用函數置放位置common檔案夾下common.php檔案(此段代碼也可放置在要使用的控制器中)
封裝的下拉式清單函數代碼:
/** * 根據列表拼裝成一個下拉式清單 ADD BY CK * @param $list :資料來源 * @param $value :顯示的option的value值,下標 例:$list[‘id‘]中的id * @param $text :顯示的option的text值 例:$list[‘name‘]中的name * @param int $selectIndex : 選中的索引項目 * @param bool $haveFirst:是否有第一項如‘<option value="0">請選擇</option>‘,預設為false * @return bool|string */ function getSelectOption($list,$value,$text,$selectIndex = 0,$haveFirst=false) { if(!is_array($list) ) { return false; } if(!isset($list)||!isset($value)||!isset($text)) { return false; } if(empty($list)||empty($value)||empty($text)) { return false; } if(!$haveFirst)//如果有第一項則不添加 { $resultStr=‘<option value="0">請選擇</option>‘; } foreach($list as $option) { if($option[$value] == $selectIndex ){ $resultStr .= ‘<option value=‘.$option[$value].‘ selected="selected">‘.$option[$text].‘</option>‘; }else { $resultStr .= ‘<option value=‘.$option[$value].‘>‘.$option[$text].‘</option>‘; } } return $resultStr; }
Exchange控制器代碼:
public function index(){$this->assign(‘option‘, array(‘prov‘ => $this->getRegion(0))); //頁面初始化擷取省份。$this->display();}
/** * 擷取省市 * @param type $pid * @param type $ajax 是否ajax調用 * @return type array */ public function getRegion($pid = 0, $ajax = false, $checked = 0, $prvcheck = false) { $r = D("Region")->where("parentid=" . $pid)->select(); //Region省市級聯表,parentid父親級id,pid自增id if ($ajax) { $this->ajaxReturn(getSelectOption($r, ‘id‘, ‘name‘)); } else { if ($prvcheck) { $prvid = D("Region")->query("SELECT id from hengtu_region where id=(SELECT parentid from hengtu_region where parentid=(SELECT parentid from hengtu_region where id=" . $pid . ") limit 1)"); return getSelectOption(D("Region")->where("parentid=0")->select(), ‘id‘, ‘name‘, $prvid[0][‘id‘]); } return getSelectOption($r, ‘id‘, ‘name‘, $checked); } }
在index頁面要顯示省市級聯的位置:
<font style="font-size:12px;">地區選擇:</font> <select id="addarea_sheng" name=‘cityid‘;> {$option.prov} </select> <select id="addarea_shi" name=‘cityid‘ style="display:none;" > </select> <select id="addarea_quxian" name=‘cityid‘ style="display:none;" > </select> <script> $("#addarea_sheng").change(function() { var provid = $("#addarea_sheng").val(); $.get("{:U(‘Exchange/getRegion‘)}?pid=" + provid + "&ajax=1", function(data) { $("#addarea_shi").show(0, function() { $(this).html(data); }); }) }) $("#addarea_shi").change(function() { var provid = $("#addarea_shi").val(); $.get("{:U(‘Exchange/getRegion‘)}?pid=" + provid + "&ajax=1", function(data) { $("#addarea_quxian").show(0, function() { $(this).html(data); }); }) })</script>
thinkPHP中省市級聯下拉式清單