## JavaScript 是WEB頁面的特效師
互聯網剛發展的時候,我們看到的頁面都是靜態的,也就是說“寫死”的,數據不會動態變化,也沒有任何的交互。就像在看一個txt文本一樣。
后來發展,有了JavaScript后,頁面中出現了各種炫麗的特效,交互,還可以動態的更新頁面結構,更新頁面數據。
JavaScript 發展后,又出現了越來越多基于JavaScript的庫,它們更加強大,并且更容易使用,我下面會以JQuery為例,進行演示。
## 使用JQuery動態更新DOM
js類似與css,既可以直接在html頁面內編寫,也可以在獨立的js文件中編寫,然后再引入到html中。
我這里為了方便,直接寫在html頁面內
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="hello.css" rel="stylesheet">
</head>
<body>
<h1 class="head_title">你好,<span id="world">世界!</span></h1>
<input id="greet" placeholder="請輸入你想說的話" required/>
<button onclick="send_msg()">提交</button>
<div class="msg">
</div>
<script>
send_msg=function () {
var content = $('#greet').val();
$('#greet').val("");
$('.msg').append("<p>"+content+"</p>");
}
</script>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依賴 jQuery,所以必須放在前邊) -->
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
```
演示結果如:

這例子,在“提交”按鈕中添加了一個點擊事件,當點擊“提交”按鈕時,執行send_msg 函數:
1. 首先獲取輸入框中的內容,賦值給content
2. 然后將輸入框清空
3. 然后獲取class為“msg”的div,往這個div中添加一個段落,包含content內容。
4. 然后直接渲染到頁面中
## 使用JQuery與服務端進行數據交互
修改前面的script部分內容如下
```html
<script>
send_msg = function () {
$.ajax({
url: "http://httpbin.org/json",
data: {},
type: "GET",
dataType: 'json',
success: function (data) {
$('.msg').append("<pre>" + JSON.stringify(data,null,4) + "</pre>");
}
}
);
}
```
修改后,演示結果如:

如圖,點擊“提交”按鈕后,js會向服務器發送一個請求,并且獲取請求的響應后,將響應的內容實時刷新到頁面的某個位置。
## 那些必須了解的js知識
**js的掌握,比css稍微要重要一些,特別是元素定位和元素操作,數據交互**
* 后期的UI自動化測試,需要熟悉元素定位
* 后期的平臺化,需要熟悉數據交互
推薦一個學習網站,請務必要認真學習并且掌握。
[http://www.runoob.com/jquery/jquery-tutorial.html](http://www.runoob.com/jquery/jquery-tutorial.html)