javascript 取不到绑定后控件的ID?大家帮忙看看,解决后马上给分,在线等
这段是Javascript脚本一起贴出来:
<script language="javascript" type="text/javascript">         
         function Add(objA,objB)
         {
             var tem=new Array();
             with(objA)
             for(i=length-1;i>=0;i--)
                 if(options[i].selected){tem[tem.length]=new Option(options[i].text,options[i].value);}              
             if(objA.selectedIndex>-1)
             {
                 for(i=0;i<objB.length;i++) tem[tem.length]=objB.options[i];
                 with(objB)
                 {
                     length=0;
                     tem.sort(sortArr);
                     for(i=0;i<tem.length;i++) options[length]=new Option(tem[i].text,tem[i].value)
                 }
             }     
         }
</script>
这段是DataList绑定代码:
<asp:DataList ID="DataList1" runat="server" Width="100%" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
  <tr>
    <td valign="top" align="left">
           <asp:ListBox ID="ListBox1" runat="server" Height="180px" Width="88px"></asp:ListBox>
    </td>
      <td style="width: 100px; text-align: center;">
       <span style="font-size: 9pt"><a href="#" onclick="Add(document.getElementById('ListBox1'),document.getElementById('ListBox2'))">添加>></a></span>   
   </td>
   <td valign="top" align="left">
           <asp:ListBox ID="ListBox2" runat="server" Height="180px" Width="88px"></asp:ListBox>
   </td>
 </tr>
</ItemTemplate>
这段代码的作用是,当我点击添加链接的时候把ListBox1的值赋给ListBox2.
当然,在这段代码没有绑定在DataList上的时候是正常的。绑定后document.getElementById('ListBox1')取出来为NULL
(红色部分javascrpt的Add方法调用的时候取不到值,值为NULL)。在查看运行出来的源代码的时候,得知DataList绑定的时候把
包含在<ItemTemplate></ItemTemplate>里的所有控件改名了,所以javascript再document.getElementById('ListBox1')
的时候找不到控件。请各位高手帮帮忙,我弄了半天了.......才上来求助的
------解决方案--------------------<span style="font-size: 9pt" > <a href="#" onclick="Add(document.getElementById( '<%=ListBox1.ClientID %> '),document.getElementById( '<%=ListBox2.ClientID%> '))" >添加>> </a > </span >     
------解决方案--------------------这里的listbox他被包含在DataList的子控件集里了 ,解析到 页面时,客户端的id已经改变(你可以点反键查看源文件),
而js代码中的id只能是客户端的id,不能是服务器端的(也就是C#中的)。
------解决方案--------------------我想到两种方法:一种在服务端来解决,一种在客户端来触决
服务器端解决:
首先,把DataList中的<a>添加>>  </a  >改成服务器端控件,如:<a href="#" id="myA" runat="server">添加</a>
然后,给DataList添加OnItemDataBound事件,在事件处理程序中,给myA添加onclick属性,如:
protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
  HtmlAnchor myA = e.Item.FindControl("myA") as HtmlAnchor;
  if (myA != null)
  {
     ListBox l1 = e.Item.FindControl("ListBox1");
     ListBox l2 = e.Item.FindControl("ListBox2");
     myA.attributes.Add("onclick", "Add(document.getElementById('" + l1.ClientID.ToString() + "'),document.getElementById('" +  l2.ClientID.ToString() + "')")
  }
}
在客户端来解决:
使用DOM,楼主