javascript 注意事项

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
    document.getElementById("demo").innerHTML="我的第一个 JavaScript 函数";
}
</script>
</head>
<body>
<h1>我的 Web 页面</h1>
<p id="demo">一个段落</p>
<button type="button" οnclick="myFunction()">尝试一下</button>
</body>
</html>

    document.getElementById("demo").innerHTML="我的第一个 JavaScript 函数";

这里 对应的是:<p id="demo">一个段落</p>

外部 js

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
  1. 使用 window.alert() 弹出警告框。
  2. 使用 document.write() 方法将内容写到 HTML 文档中。
  3. 使用 innerHTML 写入到 HTML 元素。
  4. 使用 console.log() 写入到浏览器的控制台。

window.alert(5 + 6);

document.write(Date());
document.write("2")
document.write("3");

结果:

Wed Apr 08 2020 17:24:53 GMT+0800 (中国标准时间)23

JavaScript 字母大小写

JavaScript 对大小写是敏感的。

当编写 JavaScript 语句时,请留意是否关闭大小写切换键。

函数 getElementById 与 getElementbyID 是不同的。

同样,变量 myVariable 与 MyVariable 也是不同的。

JavaScript 同样保留了一些关键字,这些关键字在当前的语言版本中并没有使用,但在以后 JavaScript 扩展中会用到。

以下是 JavaScript 中最​​重要的保留字(按字母顺序):

abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with

HTML 表单实例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("需要输入名字。");
        return false;
    }
}
</script>
</head>
<body>

<form name="myForm" action="demo_form.php"
οnsubmit="return validateForm()" method="post">
名字: <input type="text" name="fname">
<input type="submit" value="提交">
</form>

</body>
</html>
发布了647 篇原创文章 · 获赞 659 · 访问量 59万+

猜你喜欢

转载自blog.csdn.net/qq_38998213/article/details/105392127