javascript - 未捕获的类型错误 : Cannot set property 'type' of null

标签 javascript html asp.net

我在 asp.net 中使用母版页,并在 Chrome 浏览器检查工具控制台中收到以下错误。

未捕获类型错误:无法将属性“类型”设置为 null 在 myFunction (StudentPassword.aspx:258) 在 HTMLInputElement.onclick

我猜问题出在脚本标签上。我应该把它放在哪里?标签内、内容页底部或母版页底部?

母版页是:

  <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Student.master.cs" Inherits="Project_Placements.Student" %>

 <!DOCTYPE HTML>

 <HTML>
 <head runat="server">
 </head>
 <body>
 <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
  <script type="text/javascript">
   
       function myFunction() {
           var checkBox = document.getElementById("myCheck");
           var pwd = document.getElementById("password");
           if (checkBox.checked == true) {
               pwd.type = 'password';
           } else {
               pwd.type = 'text';
           }
       }
   }
   </script>    
   </body>
   </html>

内容页代码如下:

 <%@ Page Title="" Language="C#" MasterPageFile="~/Student.Master" AutoEventWireup="true" 
 CodeBehind="StudentPassword.aspx.cs" Inherits="Project_Placements.WebForm7" %>

 <asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">    
<form id="form1" runat="server">
 <asp:TextBox ID="password" runat="server"  TextMode="Password" ></asp:TextBox>
 <label for="myCheck">Show Password :</label> 
  <input type="checkbox" id="myCheck" onclick="myFunction()">
  </form>
  </asp:Content>

 

最佳答案

ASP.Net 将所有 id 从服务器端运行的父元素链接到当前元素的 id,除非在服务器上覆盖。因此输出的 id 实际上看起来像 ContentPlaceHolder1$Content3$form1$password

您可以使用结尾选择器来省略此内容。

var pwd = document.querySelector("[id$=password]").

但请注意,仍然要选择唯一的id,使用ends-with 也将是唯一的。

或者,您可以使用数据属性并选择它:

<asp:TextBox ID="password" runat="server"  TextMode="Password" data-id="password" />
var pwd = document.querySelector("[data-id=password]");

最后你可以使用类似的东西:

var pwd = document.getElementById('<%=password.ClientID %>');

但我从来没有真正喜欢它,它要求脚本内联。

关于javascript - 未捕获的类型错误 : Cannot set property 'type' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852733/

相关文章:

javascript - 浏览器问题 :Branching Select Drop Down Not Supporting in IE 7 or 8

javascript - Angular 和 ASP.NET MVC - 当我将参数传递给后端 Controller 时,参数为空

asp.net - updatepanel 只更新第一次然后不会再次更新

javascript - 合并重复列表项并相应地更改 css

javascript - 试图删除 Soltar 在 JavaScript 中生成的图像

JavaScript 正则表达式性能。

javascript - 内联脚本,因为它违反了以下内容安全策略指令 : "script-src ' self'"

javascript - 旋转图像和像素碰撞检测

java - 是否有任何使用 Mylyn WikiText 的 Java 示例?

javascript - 在 javascript 中隐藏 gridview 列时遇到问题