简体   繁体   English

从外部jscript调用document.getElementById()返回null

[英]document.getElementById() returns null when called from external jscript

I have one aspx page,which looks like this and calls the 123.js file located within the solution. 我有一个aspx页面,看起来像这样,并调用了解决方案中的123.js文件。

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="1.aspx.cs" Inherits="1"  ValidateRequest="false"%>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <script src="Scripts/123.js" type="text/javascript"></script>
    .
    .
    .
    .
    <tr>
     <td>Start DateTime</td>
     <td>
      <asp:TextBox ID="txtStartDateTime" runat="server"></asp:TextBox>                                
     </td>
     <td>                                    
       <a href="javascript:_fnSet('this', 'txtStartDateTime', 'close=true,instance=single')">                                         
       <img src="Styles/imagesCA3B3R54.jpg" alt="IMG" style="border-style: none" />                                         
       </a>
      </td>
    </tr>
</asp:Content>

This function fnSet() is located in 123.js 该函数fnSet()位于123.js中

123.js starts with 123.js始于

function _fnSet(e, sInputID, sCustom) {
    var oInput = document.getElementById(sInputID);
}

sInputID is getting the value 'txtStartDateTime' as string but, This oInput returns null. sInputID将值“ txtStartDateTime”作为字符串获取,但是此oInput返回null。

Why it is happening so..??? 为什么会这样呢.. ???

You're in a ContentPlaceHolder. 您在ContentPlaceHolder中。 By default, ASP.NET places an extra identifier in front of the Control's ID when rendered to the client. 默认情况下,当呈现给客户端时,ASP.NET在控件ID的前面放置一个额外的标识符。 This is known as the ClientID. 这称为ClientID。 You can change how the ClientID is generated by changing the ClientIDMode. 您可以通过更改ClientIDMode来更改ClientID的生成方式。 Try changing the ClientIDMode to Static. 尝试将ClientIDMode更改为Static。

<asp:TextBox ID="txtStartDateTime" ClientIDMode="Static" runat="server" />

If you're ever in doubt about what ID is being used on the client side, then view the page in your browser and view the HTML of the page that got generated. 如果您不确定客户端使用的ID是什么,请在浏览器中查看该页面并查看生成的页面的HTML。

In your web.config file, you can set ClientIdMode to be static by default. 在您的web.config文件中,可以将ClientIdMode默认设置为静态。

<pages clientIDMode="static" />

The ID of txtStartDateTime is actually different. txtStartDateTime的ID实际上不同。 Have a look at the source code. 看一下源代码。

You can get the ClientID for example like this: 您可以像这样获取ClientID的示例:

document.getElementById('<%# txtStartDateTime.ClientID %>')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM