我正在尝试在页面加载后运行一段 javascript:
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (IsPostBack)
{
string controlName = getPostBackControlName();
if (controlName == "btnSubmit" || controlName == "ddlSalary")
{
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "onLoadDisplay(this)", true);
}
}
}
这里是引用的javascript:
function onLoadDisplay(sender) {
PerDiemClicked(sender);
}
function PerDiemClicked(sender) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>').checked == true) {
document.getElementById("PerDiemDisplay").style.display = 'inline';
}
else {
document.getElementById("PerDiemDisplay").style.display = 'none';
}
}
我收到这个错误:
0x800a138f - JavaScript runtime error: Unable to get property 'checked' of undefined or null reference
我不明白为什么检查返回空值,因为我在检查之前等待页面完成回发。如何检查这个控件并正确运行上面的代码?
编辑:这里是复选框:
<asp:CheckBox ID="chkbxPerDiem" runat="server" Checked="false" onclick="PerDiemClicked(this)" />
最佳答案
您的脚本可能在 chkbxPerDiem
被添加到 DOM 之前执行.在窗口中执行脚本 load event :
window.addEventListener("load", function() {
onLoadDisplay(this);
});
试试这个:
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", @"
window.addEventListener('load', function() {
onLoadDisplay(this);
});", true);
参见 this answer
关于javascript - 页面加载后来自控件的空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27848702/