JavaScript错误:无法获取未定义或空引用的属性“样式”?

时间:2016-12-06 08:31:42

标签: javascript asp.net

我创建了带有复选框的DropDownList js中出现错误:

document.onclick = check;
function check(e) {
    var target = (e && e.target) || (event && event.srcElement);
    var obj = document.getElementById('divChkList');
    var obj1 = document.getElementById('ddlChkList');
    if (target.id != "alst" && !target.id.match("chkLstItem")) {
        if (!(target == obj || target == obj1)) {
            obj.style.display = 'none'
        }    

html:

<table>
      <tr>
            <td valign="top" style="width: 165px">
                  <asp:PlaceHolder ID="phDDLCHK" runat="server"></asp:PlaceHolder>
            </td>
            <td valign="top">
                  <asp:Button ID="btn" runat="server" Text="Get Checked" OnClick="btn_Click" />
            </td>
            <td valign="top">
                  <asp:Label ID="lblSelectedItem" runat="server"></asp:Label>
            </td>
      </tr>
</table>
<asp:HiddenField ID="hidList" runat="server" />

这是Page_load中的代码cs 我在这里定义了下拉列表:

 DropDownList ddl = new DropDownList();
        ddl.ID = "ddlChkList";
        ListItem lstItem = new ListItem();
        ddl.Items.Insert(0, lstItem);
        ddl.Width = new Unit(155);
        ddl.Attributes.Add("onmousedown", "showdivonClick()");
        CheckBoxList chkBxLst = new CheckBoxList();
        chkBxLst.ID = "chkLstItem";
        chkBxLst.Attributes.Add("onmouseover", "showdiv()");
        DataTable dtListItem = GetListItem();
        int rowNo = dtListItem.Rows.Count;
        string lstValue = string.Empty;
        string lstID = string.Empty;
        for (int i = 0; i < rowNo - 1; i++)
        {
            lstValue = dtListItem.Rows[i]["Value"].ToString();
            lstID = dtListItem.Rows[i]["ID"].ToString();
            lstItem = new ListItem("<a href=\"javascript:void(0)\" id=\"alst\" style=\"text-decoration:none;color:Black; \" onclick=\"getSelectedItem(' " + lstValue + "','" + i + "','" + lstID + "','anchor');\">" + lstValue + "</a>", dtListItem.Rows[i]["ID"].ToString());
            lstItem.Attributes.Add("onclick", "getSelectedItem('" + lstValue + "','" + i + "','" + lstID + "','listItem');");
            chkBxLst.Items.Add(lstItem);
        }
        System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
        div.ID = "divChkList";
        div.Controls.Add(chkBxLst);
        div.Style.Add("border", "black 1px solid");
        div.Style.Add("width", "160px");
        div.Style.Add("height", "180px");
        div.Style.Add("overflow", "AUTO");
        div.Style.Add("display", "none");
        phDDLCHK.Controls.Add(ddl);
        phDDLCHK.Controls.Add(div);

此处出现错误obj.style.display = 'none'

我一直在网上寻找解决方案但没有任何工作?

我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题中提供的HMTL没有ID为divChkList

的元素

即使它存在,调用ASP.net控件的正确方法也是这样的

var obj = document.getElementById('<%=divChkList.ClientID%>');

这是因为asp.net不会呈现您在server control的标记中指定的相同ID,除非指定将其保持为静态。