参考了一个别人的select生成树形,但是他是要求数据有规律的具体代码如下
function TreeSelector(item,data,rootId){
this._data = data;
this._item = item;
this._rootId = rootId;
}
TreeSelector.prototype.createTree = function(){
var len =this._data.length;
for( var i= 0;i<len;i++){
if ( this._data[i].pid == this._rootId){
this._item.options.add(new Option(".."+this._data[i].text,this._data[i].id));
for(var j=0;j<len;j++){
this.createSubOption(len,this._data[i],this._data[j]);
}
}
}
}
TreeSelector.prototype.createSubOption = function(len,current,next){
var blank = "..";
if ( next.pid == current.id){
intLevel =0;
var intlvl =this.getLevel(this._data,this._rootId,current);
for(a=0;a<intlvl;a++)
blank += "..";
blank += "├-";
this._item.options.add(new Option(blank + next.text,next.id));
for(var j=0;j<len;j++){
this.createSubOption(len,next,this._data[j]);
}
}
}
TreeSelector.prototype.getLevel = function(datasources,topId,currentitem){
var pid =currentitem.pid;
if( pid !=topId)
{
for(var i =0 ;i<datasources.length;i++)
{
if( datasources[i].id == pid)
{
intLevel ++;
this.getLevel(datasources,topId,datasources[i]);
}
}
}
return intLevel;
}如果遇到这种情况,就不能生成了,
data[0]={id:'1',pid:'0',text:'第一级'};
data[1]={id:'2',pid:'3',text:'第二级'};
data[2]={id:'3',pid:'2',text:'第三级'};
要求select显示成:
第一级
--第三级
--第二级
function TreeSelector(item,data,rootId){
this._data = data;
this._item = item;
this._rootId = rootId;
}
TreeSelector.prototype.createTree = function(){
var len =this._data.length;
for( var i= 0;i<len;i++){
if ( this._data[i].pid == this._rootId){
this._item.options.add(new Option(".."+this._data[i].text,this._data[i].id));
for(var j=0;j<len;j++){
this.createSubOption(len,this._data[i],this._data[j]);
}
}
}
}
TreeSelector.prototype.createSubOption = function(len,current,next){
var blank = "..";
if ( next.pid == current.id){
intLevel =0;
var intlvl =this.getLevel(this._data,this._rootId,current);
for(a=0;a<intlvl;a++)
blank += "..";
blank += "├-";
this._item.options.add(new Option(blank + next.text,next.id));
for(var j=0;j<len;j++){
this.createSubOption(len,next,this._data[j]);
}
}
}
TreeSelector.prototype.getLevel = function(datasources,topId,currentitem){
var pid =currentitem.pid;
if( pid !=topId)
{
for(var i =0 ;i<datasources.length;i++)
{
if( datasources[i].id == pid)
{
intLevel ++;
this.getLevel(datasources,topId,datasources[i]);
}
}
}
return intLevel;
}如果遇到这种情况,就不能生成了,
data[0]={id:'1',pid:'0',text:'第一级'};
data[1]={id:'2',pid:'3',text:'第二级'};
data[2]={id:'3',pid:'2',text:'第三级'};
要求select显示成:
第一级
--第三级
--第二级
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货