问题描述
- JS函数为定义问题,浏览器老是显示函数fun2( )未定义
-
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>改变图案的形状和颜色</title> <script type="text/javascript"> function fun1(){ document.body.innerHTML = "" for (i=0;i<12;i++) { for (j=0;j<12-i;j++) { document.write("<span style='color: red;'>*</span>"); } document.write("<br />"); } document.write("<br/><br/>"); document.write("<input type='button' value='点我有惊喜' onclick='fun2()'/>") } function fun2(){ document.body.innerHTML = " " for (i=12;i>0;i--) { for (k=0;k<12-i;k++) { document.write("  "); } for (j=0;j<i;j++) { document.write("<span style='color: greenyellow;'>*</span>"); } document.write("<br />"); } document.write("<br/><br/>"); document.write("<input type='button' value='点我有惊喜' onclick='fun1()'/>") } </script> </head> <body onload="fun1()"> </body> </html>
解决方案
文档流关闭后不要使用doucment.write,会创建新文档覆盖当前页面所有内容,包括js,用document.body.innerHTML +=
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>改变图案的形状和颜色</title>
<script type="text/javascript">
function fun1() {
document.body.innerHTML = ""
for (i = 0; i < 12; i++) {
for (j = 0; j < 12 - i; j++) {
document.body.innerHTML += ("<span style='color: red;'>*</span>");
}
document.body.innerHTML += ("<br />");
}
document.body.innerHTML += ("<br/><br/>");
document.body.innerHTML += ("<input type='button' value='点我有惊喜' onclick='fun2()'/>")
}
function fun2() {
document.body.innerHTML = " "
for (i = 12; i > 0; i--) {
for (k = 0; k < 12 - i; k++) {
document.body.innerHTML += ("  ");
}
for (j = 0; j < i; j++) {
document.body.innerHTML += ("<span style='color: greenyellow;'>*</span>");
}
document.body.innerHTML += ("<br />");
}
document.body.innerHTML += ("<br/><br/>");
document.body.innerHTML += ("<input type='button' value='点我有惊喜' onclick='fun1()'/>")
}
</script>
</head>
<body onload="fun1()">
</body>
</html>
解决方案二:
函数未定义错误排查
时间: 2024-10-31 20:28:55