如何使用JavaScript在代码文件中找到动态创建的元素

How to find a dynamically created element in the code behind file by using JavaScript

本文关键字:动态 创建 元素 JavaScript 何使用 代码 文件      更新时间:2023-09-26

我想访问JavaScript文件中的aSubchapter,我应该怎么做?(本页为内容页)

.aspx.cs文件

protected void page_load()
{
  HtmlGenericControl aSubchapter=new HtmlGenericControl("a");
  aSubchapter.Attributes.Add("href","somevalue");
  aSubchapter.ID="subchapter";
}

.aspx文件

<script type="text/javascript">
    var subchap=document.getElementById('<%=subchapter.ClientID%>');
    //(The above lines says that subchap is undefined)
</script>

由于您在后面的代码中创建了控件,因此需要将其添加到页面中。它将不可见,直到您将其添加到某个控件。

通常,您可以在.aspx文件中定义控件,并从后面的代码中将控件作为子控件添加。