使用js+jquery實現(xiàn)無限極聯(lián)動
更新時間:2013年05月23日 12:02:37 作者:
本篇文章是對可擴展的無限極聯(lián)動下拉選項的實例進行了分析介紹,需要的朋友參考下
今天工作需要寫樹形的聯(lián)動,于是寫了個可擴展的無限極聯(lián)動下拉選項
代碼寫的比較凌亂 先mark有空再整理

隨便截個圖!
先貼數(shù)據(jù)庫
| id | category_name 分類名 | pid 父分類id | orders 排序 |
|---|---|---|---|
| 1 | 22223331 | 0 | 1 |
| 2 | 2222111 | 1 | 1 |
| 12 | 44444 | 11 | 0 |
| 5 | 2222 | 1 | 1 |
| 6 | 2222 | 1 | 1 |
| 11 | 333 | 2 | 0 |
| 13 | 555555 | 12 | 0 |
頁面代碼 用的SMARTY
復制代碼 代碼如下:
<div id="select" >
<select name="category_1" id="category_1" onChange="change('category_1');">
<option>請選擇分類</option>
<!-- {foreach from=$galleryCategory item=category} -->
<option value="{$category.id}">{$category.category_name}</option>
<!-- {/foreach} -->
</select>
</div>
$galleryCategory 去數(shù)據(jù)的PHP代碼為
復制代碼 代碼如下:
$sql = " select * from yl_gallery_category where pid = 0";
$galleryCategory = $db->query($sql);
$smarty->assign("galleryCategory",$galleryCategory);
用的原生態(tài)代碼 還是比較容易理解的
然后就是關鍵的 JS代碼了function change(val) {
復制代碼 代碼如下:
var str = val; //select的id
var num; //當前級數(shù)
var id; // 分類id
num = str.substr(9,10);
//alert(num);
var nownum = parseInt(num)+1; // 將字符串轉換為數(shù)字
id = $("#"+str+"").val();
var r = /^[1-9]+[0-9]*]*$/; //正整數(shù)
if (!r.test(id)) {
//清空過時的選項
$("select").each(function(index){
if(index+1 > num) {
$(this).remove();
}
})
return false;
}
var url = 'gallery.php?act=category&pid='+id;
$.ajax({
type: "POST",
cache: false,
url: url,
datatype : 'json',
timeout : 3000,
success: function(result){
if ( result != 0) {
var html = "<select name=category_"+nownum+" id=category_"+nownum+" onChange=change('category_"+nownum+"'); >";
html += "<option>請選擇分類 </option>";
var datas = eval(result);
$.each(datas, function(i,val){
html += "<option value='"+val.id+"' >"+val.category_name+"</option>";
});
html += "</select>";
//清空過時的選項
$("select").each(function(index){
if(index+1 > num) {
$(this).remove();
}
})
$("#select").append(html);
} else {
//清空過時的選項
$("select").each(function(index){
if(index+1 > num) {
$(this).remove();
}
}) }
},
error: false
});
}
AJAX 取數(shù)據(jù)的PHP代碼
復制代碼 代碼如下:
$sql = " select * from yl_gallery_category where pid = " .$pid;
$res = $db->query($sql);
if (empty($res)) {
$res = 0;
}
echo json_encode($res);
OK 大功告成!
相關文章
jQuery效果 slideToggle() 方法(在隱藏和顯示之間切換)
slideToggle() 方法通過使用滑動效果(高度變化)來切換元素的可見狀態(tài)。2011-06-06
jQuery實現(xiàn)自定義checkbox和radio樣式
這篇文章主要介紹了jQuery實現(xiàn)自定義checkbox和radio樣式的相關資料,需要的朋友可以參考下2015-07-07
Ajax分頁插件Pagination從前臺jQuery到后端java總結
這篇文章主要從前臺jQuery到后java端總結了Ajax分頁插件Pagination的使用方法和技巧,感興趣的小伙伴們可以參考一下2016-07-07

