JavaScript学习笔记(2)
JavaScript中的注释
(1)单行注释,如:
// 输出标题:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// 输出段落:
document.getElementById("myP").innerHTML="This is my first paragraph.";
(2)多行注释,如:
/*
下面的这些代码会输出
一个标题和一个段落
并将代表主页的开始
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
注释的其他作用:阻止代码执行,如
//document.getElementById("myH1").innerHTML="Welcome to my Homepage"; document.getElementById("myP").innerHTML="This is my first paragraph.";
或
/* document.getElementById("myH1").innerHTML="Welcome to my Homepage"; document.getElementById("myP").innerHTML="This is my first paragraph."; */
JavaScript变量 变量是存储信息的容器
变量的命名:
1 必须使用字母开头
2 变量名称大小写敏感
变量的创建:
使用var关键字
变量的赋值
var = value;
如:
<!DOCTYPE html>
<html>
<body>
<script>
var pi;
pi=3.14;
var PI=3.1415926;
var name="Bill Gates";
var answer='Yes I am!';
document.write(pi + "<br>");
document.write(PI + "<br>");
document.write(name + "<br>");
document.write(answer + "<br>");
</script>
</body>
</html>
下面是一个简单的JavaScript算数例子:
<!DOCTYPE html>
<html>
<body>
<p>假设 y=5,计算 x=y+2,并显示结果。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var y=5;
var x=y+2;
var sum=document.getElementById("demo")
sum.innerHTML="x=" + x;
}
</script>
</body>
</html>