Javascript运行时错误:无法获取property 'style'动态创建的文本框的未定义引用或空
本文关键字:文本 运行时错误 未定义 引用 创建 动态 property 获取 style Javascript | 更新日期: 2023-09-27 18:13:41
我在ASP.NET C#
Code-Behind中创建了一些文本框,并试图使用简单的javascript
来样式它们,我也想从Code-Behind调用。
问题是,我得到一个Javascript
运行时错误。错误是"0x800a138f - JavaScript runtime error: Unable to get property 'style' of undefined or null reference"
我的"。Aspx "页面如下:
<head runat="server">
<title></title>
<script type="text/javascript">
function call_me(x) {
var txtbox = document.getElementById(x);
txtbox.style.backgroundColor = 'black';
txtbox.style.color = 'yellow';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
</form>
</body>
我的"c# Code-Behind"文件如下:
protected void Page_Load(object sender, EventArgs e) {
for (int i = 0; i < 5; i++) {
//textbox creation
TextBox tx = new TextBox();
tx.ID = "textbox" + i.ToString();
string client_id = tx.ClientID;
tx.Text = client_id;
//script and key creation
string key_for_javascript = "call" + i.ToString();
string script_to_load = "call_me('" + client_id + "');";
//add textbox to panel
Panel1.Controls.Add(tx);
//call script
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), key_for_javascript, script_to_load, true);
}
}
我不确定我在哪里出错或我应该如何解决这个问题。请帮帮我!
可以试试下面的代码吗
for (int i = 0; i < 5; i++)
{
//textbox creation
TextBox tx = new TextBox();
tx.ID = "textbox" + i.ToString();
string client_id = tx.ClientID;
tx.Text = client_id;
//script and key creation
string key_for_javascript = "call" + i.ToString();
string script_to_load = "call_me('" + client_id + "');";
//add textbox to panel
Panel1.Controls.Add(tx);
//call script
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(), key_for_javascript, script_to_load, true);
Page.ClientScript.RegisterStartupScript(GetType(), key_for_javascript, script_to_load, true);
}