document.getElementById() returns 从外部 JS 文件调用时为 NULL

document.getElementById() returns NULL when called from external JS file

我已经查看了与此问题相关的所有其他 questions/solutions,但找不到解决方案。

我有一个带有按钮的基本 aspx 页面。 OnClick 调用一个 JS 函数。 Javascript 函数调用 document.getElementById() 有效。然后我调用一个位于外部 JA 文件中的子函数,但同一个调用失败了。为什么?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jstest.aspx.cs" Inherits="jstest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:CheckBox runat="server" ID="RunAtStartup" OnClick="function1();" text="Click Me" />
    </div>
    </form>

    <script>
    function function1()
    {
        if (document.getElementById("<%= RunAtStartup.ClientID %>") == null)
            alert('function1 null');
        else
            alert('function1 not null');
        function2();
    }
    </script>
    <script src="./function2.js"></script>
</body>
</html>

而外部 javascript 文件 function2.js 是

    function function2() {
    if (document.getElementById("<%= RunAtStartup.ClientID %>") == null)
        alert('function2 null');
    else
        alert('function2 not null');
}

点击按钮的结果会显示function1为'not null',function2为'null'。

我试过将文档作为参数传入,但没有用。我试图做一个 function2().bind(document),但没有用。我单步执行了 javascript 调试器,看起来 function1 中的文档对象与 function2 中的文档对象相同。

提前致谢 迈克尔

据我所知,元素的名称是由 ASP.net 预处理器创建的。由于 JS 文件未在 ASP.net 中解析,因此它按字面意义对待选择器,而不是将其视为真正的元素 ID。因此,此脚本不能 运行 来自外部 JS 文件。在 ASP 文件中,它替换了

<%= RunAtStartup.ClientID %>

具有实际元素 ID。外部文件正在寻找这样的东西:

<span id="<%= RunAtStartup.ClientID %>"></span>

同样,它将 ID 视为文字字符串,就像您在未安装 ASP.net 的服务器上 运行 它一样。我的解决方案可能是将 ID 存储在 ASP.net 文件的变量中,如下所示:

var id = "<%= RunAtStartup.ClientID %>";

那么,外部JS文件可以使用如下:

var element = document.getElementByID(id);

创建变量id后,当然需要包含外部JS文件。或者,更好的解决方案是将 ID 作为函数参数传递,如下所示:

function function2(id) {
    if (document.getElementById(id) == null)
        alert('function2 null');
    else
        alert('function2 not null');
}

ASP.net 文件可以这样调用文件:

function2("<%= RunAtStartup.ClientID %>");

这允许所有 ASP.net 标签在使用 JS 代码交付给客户端之前被解析 server-side。