我在 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/