JavaScript简介:
JavaScript是世界上最流行的编程语言。这门语言适用于HTML和web,更可广泛用于服务器,pc,平板和智能手机设备。
JavaScript是脚本语言
JavaScript是一种轻量级的编程语言
JavaScript是可插入HTML页面的编程代码
JavaScript插入HTML页面后可由现代的所有浏览器所执行
JavaScript的使用:
HTML中的脚本必须在<script></script>标签之间
脚本可放置在<body><head>部分中
<script>标签:
在HTML中插入javascript,必须使用<script>标签
<script></script>标签会告诉javascript在何处开始和结束
<script></script>之间的代码行包含了javascript
<script>
alert("hello");
</script>
您不必理解写的是什么,只需知道浏览器会解释并执行<script></script>里面的代码。有的例子会在<script>标签里使用type="text/javascript",现在已经不用这样做了,JavaScript是现代所有浏览器以及HEML5的默认脚本语言。
<body>中的JavaScript:
在本例中,javascript会在页面加载时向html中写入文本
<html>
<body>
<script>
document.write("<p>hello word</P>");
</script>
</body>
</html>
JavaScript的函数和事件:
上面例子中的javascript代码会在页面加载时执行
通常我们需要在某个事件发生时候执行,比如点击按钮,如果我们把javascript代码放入函数中,就可以在事件发生时调用该函数即可。
<head>和<body>中的JavaScript
您可以在html文档中放入不限数量的脚本
脚本可放于<body><head>部分中,或者同时存在于两个部分中
通常的做法是把函数放于<head>中,或者放于页面底部,这样就可以把他们安置在同一处位置,不会对页面造成任何干扰。
<head>中的JavaScript函数
在本例中,我们把javascript函数放在<head>中,在点击按钮时被调用
<html>
<head>
<script>
function myFunction(){
document.getElementById("demo").innerHTML="my first function";
}
</script>
</head>
<body>
<p id="demo" > my function</p>
<button type ="button" onclick="myFunction()">点击</button>
</body>
</html>
<body>中的JavaScript
在本例中,我们把JavaScript放在<body>中,点击按钮的时候被调用
<pre name="code" class="javascript"><html>
<body>
<p id="demo">body中的JavaScript<p>
<button type="button" onclick="myFunction()">点击</button>
<script>
function myFunction(){
document.getElementById("demo").innerHTML="你好,javascript";
}
</script>
</body>
</html>
外部的JavaScript
也可以把脚本保存到外部的文件中,外部文件通常包含被多个网页使用的代码
外部的JavaScript文件的拓展名是.js。
实例:
<html>
<body>
<script src="myJavascript.js"></script>
</body>
</html>
JavaScript 输出
JavaScript通常用于操作HTML元素
操作html元素
如需从JavaScript里访问某个HTML元素,您可以使用document.getElementById(id);
使用id属性来标识HTML元素
下面的例子是直接把<p>元素写到文档中
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script>
</body>
</html>
警告:
使用document.write()仅仅是向文档输出
如果在整个文档加载完后执行document.write(),整个html页面将被覆盖
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">点击这里</button>
<script>
function myFunction()
{
document.write("糟糕!文档消失了。");
}
</script>
</body>
</html>