原始代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>函数</title>
<!-- <link rel="icon" >-->
</head>
<body>
<script>
<!-- 第一种方式-->
function hello1(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
//第二方式
hello2 = function(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
//调用的第二种方式
document.getElementById("btn").onclick = function(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
</script>
<input type="text" name="username" id="user-name-label">
<input type="button" name="btn_1" value="提交1" onclick="hello1()">
<input type="button" name="btn_2" value="提交2" onclick= hello2()>
<input type="button" name="btn_3" value="提交3" id="btn">
</body>
</html>
出现:Cannot set property 'onclick' of null”的问题,问题出在:document.getElementById("btn").onclick = function(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
经过了解:是因为我的JS文件引入的顺序比标签加载的早,把js文件的引入放到了body下,但是依然报错。多处查询后,解决办法如下:
网页中的javaScript脚本代码往往需要在文档加载完成后才能够去执行,否则可能导致无法获取对象的情况,为了避免这种情况的发生,可以使用以下两种方式:
①通过window.onload来执行脚本代码。window.onload是一个事件,当文档加载完成之后就会触发该事件,可以为此事件注册事件处理函数,并将要执行的脚本代码放在事件处理函数中,于是就可以避免获取不到对象的情况。1:window.οnlοad=function(){},使用此种方式为window.onload事件绑定事件处理函数,这里绑定的是一个匿名函数,当然也可以绑定非匿名函数。
②可以使用addEventListener()和attachEvent()为onload事件绑定事件处理函数,addEventListener()是当前标准的一种事件处理函数绑定方式,但是IE8和IE8以下的浏览器并不支持此方式(addEventListener("type",函数名,false))。
经修改,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>函数</title>
<!-- <link rel="icon" >-->
</head>
<body>
<script>
<!-- 第一种方式-->
function hello1(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
//第二方式
hello2 = function(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
//调用的第二种方式\
window.onload = function(){
document.getElementById("btn").onclick = function(){
const text = document.getElementById("user-name-label");
// 通关判断长度来判断是否为null
if (!text.value.length){
alert("输入不能为空");
}else {
alert("欢迎你,"+text.value);
}
}
}
</script>
<input type="text" name="username" id="user-name-label">
<input type="button" name="btn_1" value="提交1" onclick="hello1()">
<input type="button" name="btn_2" value="提交2" onclick= hello2()>
<input type="button" name="btn_3" value="提交3" id="btn">
</body>
</html>