《中级前端1.1》JavaScript基础教程——保留字,数据类型,异常捕获,事件,DOM
保留字:
JavaScript数据类型:
数组定义和读取:
<script> var string = "hello"; var arr = [1, 2, 3, 4]; document.write(arr[1]); arr[4] = 76; document.write(arr[4]); var arr2 = ["hello", "my", "world"]; var arr3 = new Array("hello", "my", "world"); var arr4 = new Array(); arr4[0] = 10; arr4[1] = 20; arr4[2] = 30; document.write(arr4[1]); </script>
JavaScript对函数和变量名称的大小写非常敏感,不能写错!
异常捕获try,catch:
<form> <input type="text" name="" id="txt" value="" /> <input type="button" name="" id="btn" value="按钮" onclick="demo()" /> </form> <script> function demo() { try { var t = document.getElementById("txt").value; if (t == "") { throw "请输入"; } } catch (e) { //TODO handle the exception alert(e); } } </script>
JavaScript事件:
Javascript-DOM EventListener
<button id="btn">按钮</button> <script> var x = document.getElementById("btn"); x.addEventListener("click", hello); //句柄 x.addEventListener("click", world); //句柄 x.removeEventListener("click", hello); function hello() { alert("Hello"); } function world() { alert("World"); } </script>