知识点:
-
<script>标签调用JS
The
<script>
HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The<script>
element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.<script src="javascript.js"></script>
-
alert 警示框
alert在英语中的意思是“警告”,javascript中,alert()指的是在浏览器中弹出一个警告框,有3种不同的呈现方式,所呈现的效果也不相同。
[window.alert()
instructs](Window.alert() - Web APIs | MDN) the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.alert() alert(message)
-
函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块。
当调用该函数时,会执行函数内的代码。可以在某事件发生时直接调用函数(比如当用户点击按钮时),并且可由 JavaScript 在任何位置进行调用。
function myFunction(var1,var2) { 代码 }
JavaScript 对大小写敏感。关键词 function 必须是小写的,并且必须以与函数名称相同的大小写来调用函数。
JavaScript
脚本语言比较特殊,相对于C语言,它的参数是不需要数据类型加持的。返回值return
如果没写他就会自动返回undefined
-
onload 事件属性
JavaScript 中的函数方法需要在 HTML 文档渲染完成后才可以使用,如果没有渲染完成,此时的 DOM 树是不完整的,这样在调用一些 JavaScript 代码时就可能报出"undefined"错误。
window.onload() 方法用于在网页加载完毕后立刻执行的操作,即当 HTML 文档加载完毕后,立刻执行某个方法。通常用于 <body> 元素,在页面完全载入后(包括图片、css文件等等)执行脚本代码。
window.onload=function(){ Func1(); Func2(); Func3(); ..... }
-
onclick 事件属性
The **
onclick
**attribute specifies some script to run when the element is clicked.<svg viewBox="0 0 200 200" xmlns="<http://www.w3.org/2000/svg>"> <circle cx="100" cy="100" r="100" onclick="alert('You have clicked the circle.')" /> </svg>
-
Document
的方法getElementById()
返回一个匹配特定 ID的元素。由于元素的 ID 在大部分情况下要求是独一无二的,这个方法自然而然地成为了一个高效查找特定元素的方法。对“Id”的拼写一定要正确。如果大小写不匹配,无论看起来多么合情合理,
getElementByID()
都是不合理的且永远都不会工作的var element = document.getElementById(id);
实操案例:
一个点击微笑的石头案例
<!DOCTYPE html>
<html>
<head>
<title>irock</title>
<script type="text/javascript">
function touchRock(){
var userName = prompt("What's your name?", "Enter your name here.");
if(userName){
alert("It is good to meet you," + userName + ".");
document.getElementById("rockImg").src = "rock_happy.png";
}
}
</script>
</head>
<body onload="alert('Hello, I am your pet rock.');">
<div style="margin-top: 100px; text-align: center;">
<img id="rockImg" src="rock.png" alt="iRock" style="cursor: pointer" onclick="touchRock();"/>
</div>
</body>
</html>