当前位置: 代码迷 >> Web前端 >> checkbox级联取舍
  详细解决方案

checkbox级联取舍

热度:106   发布时间:2012-11-22 00:16:41.0
checkbox级联选择

?

今天需要级联选择子元素,我JavaScript很烂,也没系统的学过,以前总觉得JavaScript没什么意思不愿学,但现在做web开发又离不了,ajax又用的这么多,才感觉自己当初太挑食了。网上查了一下,写了个函数实现如下:

function selectSon(sel){
??for(var i=0;i<document.all("nodeid").length;i++){??
??? if(document.all("nodeid")[i].getAttribute("parentId")==sel.id)??
??? document.all("nodeid")[i].checked=sel.checked;
??? }
?}

?

jsp代码:

...

?<td class="rightTd">
???????<table>?????????????
????????<%
?????????for (int i = 0; i < nodeList.size(); i++) {
????????%>????????
?????????<%if(((String)((Map) nodeList.get(i)).get("type")).trim().equals("2")){ %>
?????????<tr>
?????????<td width="30%">
??????????<input type="checkbox" name="node<%=i%>" id="node<%=i%>" onclick="selectSon(this)"
??????????value=""/><%=((Map) nodeList.get(i)).get("name")%>
?????????</td>
?????????<td>
??????????<%?
???????????int b=0;
???????????for (int j = 0; j < nodeList.size(); j++) {???????????
???????????if(((Integer)((Map) nodeList.get(j)).get("parentid")).intValue()==(Integer)((Map) nodeList.get(i)).get("id")){
???????????b++;???????????
??????????%>?<%if(b!=0&&b%4==0){%><br><%} %>
???????????<input type="checkbox" name="nodeid"
???????????value="<%=((Map) nodeList.get(j)).get("id")%>" parentId="node<%=i%>"/><%=((Map) nodeList.get(j)).get("name")%>??????????????????????
??????????<%}}%>???????????????????
?????????</td>
?????????</tr>?????????
?????????<%}}%>?????????
???????</table>??????
??????</td>?

...

上面的都是项目里面直接复制的,挺丑的,直接拷过来了,以备以后需要。

要级联选择时,关键是子元素要定义一个父id,将父与子关联起来(红色显示),在上面的JavaScript函数中的就是这句:

document.all("nodeid")[i].getAttribute("parentId")==sel.id;

其中sel就是父元素,当onclick()时就会触发关联,并将子元素的checked属性设置为与父元素相同就行了,如下:

document.all("nodeid")[i].checked=sel.checked。

?

?

?

  相关解决方案