html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装title>
head>
<body>
<script type="text/javascript">
function jQuery(selector){
if(selector.charAt(0)=="#")
{
let domObj=document.getElementById(selector.substring(1))
return domObj
}
}
Window.onload=function(){
jQuery("#btn").onclick=function(){
jQuery("#div1").innerHTML="用户名不可用。"
}
}
script>
<button id="btn">输入用户名button>
<div id="div1">div>
body>
html>
初学前端封装函数,进行了一个小练习,但在单击按钮后结果无法显示文字,求解答哪里出错了呢
window的拼写错误,第一个w小写
“Devil组”引证GPT后的撰写:
你将 Window.onload 的 W 大写了,导致代码无法执行 onload 函数。另外,jQuery 函数没有处理 selector 参数不是以 # 开头的情况,这可能会导致函数返回 undefined。
修改后
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装</title>
</head>
<body>
<script type="text/javascript">
function jQuery(selector){
if(selector.charAt(0)=="#")
{
let domObj=document.getElementById(selector.substring(1))
return domObj
}
return null;
}
window.onload=function(){
jQuery("#btn").onclick=function(){
jQuery("#div1").innerHTML="用户名不可用。"
}
}
</script>
<button id="btn">输入用户名</button>
<div id="div1"></div>
</body>
</html>
将 Window.onload 改为 window.onload,同时在 jQuery 函数中添加了一个 return null 语句来处理无效的选择器。
Window改成小写 window