企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 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> ``` 演示结果如: ![](https://box.kancloud.cn/551472e400fc4ff7e12a3f51ab881e38_865x290.jpg) 这例子,在“提交”按钮中添加了一个点击事件,当点击“提交”按钮时,执行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>"); } } ); } ``` 修改后,演示结果如: ![](https://box.kancloud.cn/dbe25af563f29d8dc262eb24f0e71110_922x665.jpg) 如图,点击“提交”按钮后,js会向服务器发送一个请求,并且获取请求的响应后,将响应的内容实时刷新到页面的某个位置。 ## 那些必须了解的js知识 **js的掌握,比css稍微要重要一些,特别是元素定位和元素操作,数据交互** * 后期的UI自动化测试,需要熟悉元素定位 * 后期的平台化,需要熟悉数据交互 推荐一个学习网站,请务必要认真学习并且掌握。 [http://www.runoob.com/jquery/jquery-tutorial.html](http://www.runoob.com/jquery/jquery-tutorial.html)