在开发中,经常遇到诸如省、市,大类、小类的级联select 下拉框。常常,这些类别或地区的内容,又存在数据库中。因为用户希望,一切都是可控制的。那么,如果涉及到这种级联的地方,每次都人从库中读取,在JSP中要写很多代码去读表。另外,这种级联在修改数据的时候,应设置的选中项为库中所载,这也是需要写一些代码的。
这里本人建议,通过IO,将类别生成js文件,然后在页面中引入这个js文件,这样即提高的程序的运用速度,又精简了的代码书写量。
一、表结构如下:
create table news_class200
(
id int primary key,
parent_id int,
class_name varchar(20),
orderby int default 0
)
id 为自动增长
parent_id 用来标识父类的id
class_name 类别名称
orderby 排序,用来控制select中元素的前后顺序
二、成生js的java代码:
public static void news_class(String str,String tab) throws IOException
{
//大类名称
String big="big_class";
String small="small_class";
String big_array="";
String[] small_array;
Jdata data = new Jdata();//dao对象
List list = data.jlist("select * from "+tab+" where parent_id=0");
FileWriter fw = new FileWriter(str);
PrintWriter out = new PrintWriter(fw);
List ll = new ArrayList();
small_array=new String[list.size()];
for(int i=0;i {
//读取大类信息
Map map=(Map)list.get(i);
big_array+="'"+map.get("class_name")+"',";
ll=data.jlist("select * from "+tab+" where parent_id="+map.get("id"));
small_array[i]="";
for(int j=0;j {
Map m =(Map)ll.get(j);
small_array[i]+="'"+m.get("class_name")+"',";
}
small_array[i]=noEnd(small_array[i]);
// System.out.println(big_array);
}
big_array=noEnd(big_array);
// out.println("");
out.flush();
out.close();
fw.close();
}
三、生成的js如下:
document.writeln('
document.writeln('
document.writeln('');
document.writeln('
document.writeln('
document.writeln('');
var big_className = ['县域动态','省域见闻','国外新闻'];
var big_classValue=['县域动态','省域见闻','国外新闻'];
var small_class1 = ['A类',''B类,'C类'];
var small_class2 = ['无小类'];
var small_class3 = ['无'];
function big_class() {
var e = document.getElementById('big_class');
for (var i=0; i e.options.add(new Option(big_className[i], big_classValue[i]));
}
function small_classMM(n){
var e = document.getElementById('small_class');
e.options.length = 1;
if (n == 0) return;
var a = eval('small_class'+ n);
for (var i=0; i}
big_class();