Javascript 未捕获的TypeError:无法将属性“type”设置为null
我正在asp.net中使用母版页,并在chrome浏览器检查工具控制台中收到以下错误 未捕获的TypeError:无法将属性“type”设置为null 在myFunction StudentPassword.aspx:258 在HTMLInputElement.onclick 我想问题在于script标签。我应该把它放在哪里?内部标签、内容页底部还是母版页底部 母版页为:Javascript 未捕获的TypeError:无法将属性“type”设置为null,javascript,html,asp.net,Javascript,Html,Asp.net,我正在asp.net中使用母版页,并在chrome浏览器检查工具控制台中收到以下错误 未捕获的TypeError:无法将属性“type”设置为null 在myFunction StudentPassword.aspx:258 在HTMLInputElement.onclick 我想问题在于script标签。我应该把它放在哪里?内部标签、内容页底部还是母版页底部 母版页为: <%@ Master Language="C#" AutoEventWireup="
<%@ 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>
出现错误是因为在DOM完全呈现之前加载了脚本。尝试将脚本的内容放在document.ready中,这应该可以解决问题。ASP.Net将服务器端运行的父元素的所有id链接到当前元素的id,除非在服务器上被覆盖。所以输出的id实际上看起来像ContentPlaceholder 1$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 %>');
但是我从来没有真正喜欢过它,它要求脚本内联。这是否回答了您的问题?var pwd=document.querySelector[id$=myCheck]。省略服务器端生成的父id链。谢谢,@Lain。问题是runat=servers的元素的id与所有父元素链接在一起,除非通过覆盖阻止。因此,输出的id类似于ContentPlaceholder 1$Content3$form1$password。