Python自动化运维 - day15 - jQuery基础

本文介绍了jQuery的基础知识,包括jQuery的功能特点、引入方式、标签查找、属性操作、事件绑定等内容。

Python自动化运维 - day15 - jQuery基础

jQuery介绍

jQuery作为一个JavaScript函数库,极大地简化了JavaScript 编程。

什么是 jQuery ?

通俗的话来讲的话:jQuery是一个轻量级的"写的少,做的多"的JavaScript库。

它包含但不仅限于以下功能:

  • HTML 元素选取
  • HTML 元素操作
  • CSS 操作
  • HTML 事件函数
  • JavaScript 特效和动画
  • HTML DOM 遍历和修改
  • AJAX

为什么使用 jQuery ?

目前网络上有大量开源的 JS 框架, 但是 jQuery 是目前最流行的 JS 框架,而且提供了大量的扩展。

兼容性

jQuery 版本 2 以上不支持 IE6,7,8 浏览器。如果需要支持 IE6/7/8,可以使用1.9版本。

如何引入jQuery?

只需要在你的代码中,像引入其他js文件一样即可。当然你可以选择下载jQuery文件,然后引入,又或者使用提供的CDN进行引入。

// 本地文件 
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>


// 百度CDN
<head>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>

其他的静态资源CDN如:

http://cdn.code.baidu.com     // 百度的,版本较老
http://www.bootcdn.cn/jquery/     // 国内其他CDN站,版本较新

用CDN的优势时,如果用户访问的其他站点,已经保存了对应的资源,那么访问我们网站就可以直接使用缓存了。

jQuery的使用

鉴于jQuery是一个javascript的类库,它内部封装了很多javascript的操作,接下来的基本使用,会结合这javascript,对javascript不熟的请查看上一篇javascript基础。

在javascript中,我们主要的操作逻辑是查找标签,然后对其做一些函数或者参数的绑定,以及动态效果。所以在javascript存在一个标签的DOM对象,就是我们通过document.getElementXXXX找到的标签对象。

在jQuery中是一样的逻辑,只不过jQuery整体做了一个封装,在页面上,使用jQuery关键字或者使用$,表示使用jQuery对象($ == jQuery)。

// javascript
var tag = document.getElementById('id1')

// jQuery
var tag = $('#id1') 或者  jQuery('#id1')

PS:jQuery是javascript的封装,所以说,它俩是可以互相转换的。

// jQuery      -->  javascript
$('id1')[0]

// javascript  -->  jQuery
var d = document.getElemetById('id1')
$(d)

根据上面的例子得知,jQuery查找到的东西,比javascript要更多一些。

标签的查找

可以说jQuery封装的标签查找,和css的标签查找很像,只需要在$()添加选择器即可。

常用的标签查找

$('.class')           // 按照class查找
$('#id')              // 按照id查找
$('tagname')          // 按照标签名查找
$('a,.class')         // 组合选择器,只需要用逗号隔开即可
$('#id tagname')      // 查找目前标签的子孙中包含,标签类型是tagname的标签
$('#id > child')      // 在目标标签中,只查找儿子标签
$('#id + next')       // 目标标签的下一个标签
$('#id ~ siblings')   // 目标标签的之后的所有兄弟标签(同级)

常用的组合筛选器

$('a:first')     // 找到的标签中的第一个
$('a:last')      // 找到的a标签的最后一个,前面可以是任意标签选择器

// 根据上面的例子可以得知,筛选器就是在标签后面使用:分割,然后添加一些筛选的功能
:even            // 表示奇数的标签
:odd             // 表示偶数的标签
:eq(index)       // 使用索引进行过滤,索引值从0开始 (有些方法索引并不是从0开始的)
:lt(index)       // 索引小于多少的,不包含index本身
:gt(index)       // 索引大于多少的,不好含index本身

常用属性选择器

$('[属性]')        // 查找所有具有属性名的标签
$("[属性='值']")   // 根据属性对应的值进行查找
$("a[属性='值']")  // 查找a标签中属性对应的值的标签,可以组合其他类型的选择器

表单选择器

$(':input')         // 查找form中 所有的input标签
$(':text')          // 其他的类似
$(':password') 
$(':radio')
$(':checkbox')
$(':image')
$(':file')
$(':button')

表单对象属性

$(':enabled')      // 具有enabled属性的标签,input默认的属性,表示可以编辑
$(':disabled')     // 具有disabled属性的标签,input的属性,表示不可以编辑
$(':checked')      // 具有ckecked属性的表壳,比如checkbox默认的选中
$(':selected')     // 具有selected属性的标签,比如select的默认选中

筛选器

对查找到的标签进行二次筛选等

PS:jQuery支持链式调用,即可以在一行中组合多个筛选器或者赋值操作等。简而言之就是可以一直点下去。

过滤

eq(index|-index)     // 筛选索引等于几的标签,和前面说的:eq() 没有实质上的区别,要说有,就是写法不同而已。
first()              // 查找出来的第一个标签
last()               // 最后一个标签
hasClass(class)      // 筛选具有class的标签

例子:

$('.header').last()     // last的括号里面不能加额外的选择器
$('.header').first()    // 同上

筛选

children([expr])      // 所有的孩子标签
find(e|o|e)           // 在孩子中查找某一个标签
next([expr])          // 查找到标签的下一个标签
nextALL([expr])       // 查找到标签的下面的所有标签,同级别
nextUntil([expr])     // 查找到标签的下面直到某个标签
parent([expr])        // 查找到的标签的父亲
parents([expr])       // 嵌套时的所有父亲标签,默认到html
parentsUntil([expr])  // 嵌套时的所有父亲标签直到某个标签
prev([expr])          // 查找到标签的上一个标签
prevALL([expr])       // 查找到标签的上面的所有标签,同级别
prevUntil([expr])     // 查找到标签的上面的直到某个标签
siblings([expr])      // 查找到标签的所有兄弟标签
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .menu {
 8             border: 1px red solid;
 9             width:300px;
10             height: 600px;
11         }
12         a{
13             display: block;
14         }
15         .header{
16             background: darkgray;
17         }
18         .hide {
19             display: none;
20         }
21     </style>
22 </head>
23 <body>
24     <div class="menu">
25         <div class="item">
26             <div class="header">菜单1</div>
27             <div class="content">
28                 <a href="#">1</a>
29                 <a href="#">1</a>
30                 <a href="#">1</a>
31             </div>
32         </div>
33         <div class="item">
34             <div class="header">菜单2</div>
35             <div class="content hide">
36                 <a href="#">2</a>
37                 <a href="#">2</a>
38                 <a href="#">2</a>
39             </div>
40         </div>
41         <div class="item">
42             <div class="header">菜单3</div>
43             <div class="content hide">
44                 <a href="#">3</a>
45                 <a href="#">3</a>
46                 <a href="#">3</a>
47             </div>
48         </div>
49     </div>
50 
51     <script src="jquery-3.1.1.js"></script>
52     <script>
53         $('.header').click(function () {   // 不用进行循环,jQuery在内部会循环的绑定事件
54             $(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide');  // 链式操作
55         })
56     </script>
57 
58 </body>
59 </html>
左侧菜单(链式操作)

循环

 当我们查找到多个标签后做批量操作的话,javascript就需要进行循环才能批量操作了,而在jQuery中针对不同的情况有两种形式:

// 方式1
如果对多个标签做批量相同操作,那么直接调用对应的方法即可(方法内部会进行循环操作)

// 方式2
如果不不是批量操作,比如有条件的操作就需要使用each方法
$('.class').each(function(k) {       // 这里的k表示索引,可以接受,也可以不接受,看需求
     console.log(this)               // 这里的this表示的就是当前循环的标签本身,是一个DOM对象
     $(this)                         // 就可以把DOM对象转换为jQuery对象
})
// each接受一个函数,表示每次循环都执行这个函数
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <input type="button" value="全选" onclick="checkALL()">
 9 <input type="button" value="反选" onclick="reverseALL()">
10 <input type="button" value="取消" onclick="cancelALL()">
11 <table border="1px" id="tb">
12     <thead>
13     <tr>
14         <th>序号</th>
15         <th>IP</th>
16         <th>端口</th>
17     </tr>
18     </thead>
19     <tbody id="tbody">
20     <tr>
21         <td><input type="checkbox"></td>
22         <td>1.1.1.1</td>
23         <td>80</td>
24     </tr>
25     <tr>
26         <td><input type="checkbox"></td>
27         <td>2.2.2.2</td>
28         <td>8080</td>
29     </tr>
30     <tr>
31         <td><input type="checkbox"></td>
32         <td>3.3.3.3</td>
33         <td>8443</td>
34     </tr>
35     </tbody>
36 </table>
37 <script src="jquery-3.1.1.js"></script>
38 <script>
39     function checkALL() {
40         // $(':checkbox')  也可以,但是如果页面上的checkbox多了,就不太好了
41         $("#tbody input[type='checkbox']").prop('checked', true);
42     }
43     function cancelALL() {
44         $("#tbody input[type='checkbox']").prop('checked', false);
45     }
46     function reverseALL() {
47         $("#tbody input[type='checkbox']").each(function () {
48            if ($(this).prop('checked')) {
49             $(this).prop('checked',false)
50         } else {
51             $(this).prop('checked',true)
52         }
53         })
54 
55     }
56 </script>
57 </body>
58 </html>
全选反选取消

PS:jQuery对象.prop() 针对于selected/checked,用来获取其值,选中表示true,否则表示false,当传递一个参数时表示获取,两个参数时表示设置。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <input type="button" value="全选" onclick="checkALL()">
 9 <input type="button" value="反选" onclick="reverseALL()">
10 <input type="button" value="取消" onclick="cancelALL()">
11 <table border="1px" id="tb">
12     <thead>
13     <tr>
14         <th>序号</th>
15         <th>IP</th>
16         <th>端口</th>
17     </tr>
18     </thead>
19     <tbody id="tbody">
20     <tr>
21         <td><input type="checkbox"></td>
22         <td>1.1.1.1</td>
23         <td>80</td>
24     </tr>
25     <tr>
26         <td><input type="checkbox"></td>
27         <td>2.2.2.2</td>
28         <td>8080</td>
29     </tr>
30     <tr>
31         <td><input type="checkbox"></td>
32         <td>3.3.3.3</td>
33         <td>8443</td>
34     </tr>
35     </tbody>
36 </table>
37 
38 
39 <input type="text" id ='id3'>
40 <script src="jquery-3.1.1.js"></script>
41 <script>
42     function checkALL() {
43         // $(':checkbox')  也可以,但是如果页面上的checkbox多了,就不太好了
44         $("#tbody input[type='checkbox']").prop('checked', true);
45     }
46     function cancelALL() {
47         $("#tbody input[type='checkbox']").prop('checked', false);
48     }
49     function reverseALL() {
50         $("#tbody input[type='checkbox']").each(function () {
51             var v = $(this).prop('checked')?false:true  // 为真时赋值false,为假时赋值true。达到取反的功能
52             $(this).prop('checked',v)
53         })
54     }
55 </script>
56 </body>
57 </html>
全选反选取消 - 三元表达式

标签操作

对找到的标签进行操作,比如属性的添加,文本的修改,样式的修改等

创建标签

var li = $('<li>');         // 创建一个jQuery标签对象li
li.text(test);              // 设置li标签的value
li.attr('name','daxin');    // 设置li标签的name属性

文本内容操作

$(..).text('string')     // 不加参数表示获取标签内的文本内容,添加参数表示设置文本内容
$(..).html('string or label')    // 不加参数表表示获取标签内的内容,包含html标签,添加参数表示设置标签内容

// 针对input系列来说
$(..).val()  // 不加参数表示获取标签输入框的内容,添加参数表示设置数据框内容
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .hide {
  8             display: none;
  9         }
 10 
 11         label {
 12             display: inline-block;
 13             width: 70px;
 14             text-align: right;
 15         }
 16 
 17         .motaibutton {
 18             width: 200px;
 19             text-align: right;
 20         }
 21 
 22         .motaiback {
 23             position: fixed;
 24             top: 0;
 25             bottom: 0;
 26             right: 0;
 27             left: 0;
 28             opacity: 0.6;
 29             background-color: #000000;
 30             z-index: 9;
 31         }
 32 
 33         .motaiinfo {
 34             width: 400px;
 35             height: 300px;
 36             position: fixed;
 37             top: 50%;
 38             left: 50%;
 39             margin-top: -150px;
 40             margin-left: -200px;
 41             background-color: white;
 42             z-index: 10;
 43         }
 44     </style>
 45 </head>
 46 <body>
 47 
 48 <input type="button" value="添加" id="addFunc">
 49 <table border="1px">
 50     <thead>
 51     <tr>
 52         <th>序号</th>
 53         <th>IP</th>
 54         <th>Port</th>
 55         <th>操作</th>
 56     </tr>
 57     </thead>
 58     <tbody>
 59     <tr>
 60         <td>1</td>
 61         <td>1.1.1.1</td>
 62         <td>80</td>
 63         <td><input class='modifyFunc' type="button" value="编辑"></td>
 64     </tr>
 65     <tr>
 66         <td>2</td>
 67         <td>2.2.2.2</td>
 68         <td>8080</td>
 69         <td><input class='modifyFunc' type="button" value="编辑"></td>
 70     </tr>
 71     <tr>
 72         <td>3</td>
 73         <td>3.3.3.3</td>
 74         <td>8443</td>
 75         <td><input class='modifyFunc' type="button" value="编辑"></td>
 76     </tr>
 77     </tbody>
 78 </table>
 79 
 80 <div class="motaiback hide"></div>
 81 <div class="motaiinfo hide">
 82     <p>
 83         <label for="hostname">主机IP:</label>
 84         <input type="text" id="hostname">
 85     </p>
 86     <p>
 87         <label for="port">端口:</label>
 88         <input type="text" id="port">
 89     </p>
 90     <div class='motaibutton'>
 91         <input type="button" value="确定">
 92         <input type="button" value="取消" id="cancelFunc">
 93     </div>
 94 
 95 </div>
 96 
 97 
 98 <script src="jquery-3.1.1.js"></script>
 99 <script>
100     $('#addFunc').click(function () {
101         $('.motaiback,.motaiinfo').removeClass('hide')
102     });
103 
104     $('#cancelFunc').click(function () {
105         $('.motaiback,.motaiinfo').addClass('hide');
106         $(".motaiinfo input[type ='text']").val('');     // 取消时删除模态框中标签的内容
107     });
108 
109     $('.modifyFunc').click(function () {
110         $('.motaiback,.motaiinfo').removeClass('hide'); 
111         var td_list = $(this).parent().prevAll();      // 获取本行其他标签的值
112         var port = $(td_list[0]).text();
113         var hostname = $(td_list[1]).text();
114         $('#hostname').val(hostname);
115         $('#port').val(port);
116     })
117 </script>
118 </body>
119 </html>
模态对话框之编辑

class类操作

$(..).addClass('className')            // 为标签对象添加class属性
$(..).removeClass('className')         // 为标签对象移除class属性
$(..).hasClass('className')            // 判断标签是否含有class属性,返回bool
$(..).toggleClass('className')         // 如果标签对象存在class属性那么会删除,不存在则加上
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         body {
 8             background-color: #000000;
 9         }
10 
11         .white {
12             background-color: white;
13         }
14     </style>
15 </head>
16 <body>
17 <input type="button" value="开灯" id="switch">
18 </body>
19 <script src='jquery-3.1.1.js'></script>
20 <script>
21     $('#switch').click(function () {
22         $('body').toggleClass('white');
23     });
24 
25     // 效果等同于
26     $('#switch').click(function () {
27         if ($('body').hasClass('white')) {
28             $('body').removeClass('white')
29         } else {
30             $('body').addClass('white')
31         }
32     });
33 
34 
35 </script>
36 </html>
开灯关灯效果

属性操作

$(..).attr('value')        // 用来获取自定义属性的值
$(..).attr('value','值')   // 用来设置标签的属性及其值
$(..).removeAttr('value')  // 删除标签的属性
$(..).prop('checked')               // 专门用于checkbox,radio,设置checked等属性的
$(..).prop('checked',true)  

注意:

  1、虽然我们可以利用attr(),来设置checkbox的checked等属性(select的selected),但是在jQuery的1,2版本,会有bug,即:多次选中取消,会失效(3版本已经修复了)

  2、针对checked类似的这种属性,使用prop()即可。

前面的模态对话框之编辑框中,获取表示是通过索引进行获取的,如果html元素进行修改,那么js也要做相应的修改,这太不方便了,所以进行如下修改,基于属性的操作:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .hide {
  8             display: none;
  9         }
 10 
 11         label {
 12             display: inline-block;
 13             width: 70px;
 14             text-align: right;
 15         }
 16 
 17         .motaibutton {
 18             width: 200px;
 19             text-align: right;
 20         }
 21 
 22         .motaiback {
 23             position: fixed;
 24             top: 0;
 25             bottom: 0;
 26             right: 0;
 27             left: 0;
 28             opacity: 0.6;
 29             background-color: #000000;
 30             z-index: 9;
 31         }
 32 
 33         .motaiinfo {
 34             width: 400px;
 35             height: 300px;
 36             position: fixed;
 37             top: 50%;
 38             left: 50%;
 39             margin-top: -150px;
 40             margin-left: -200px;
 41             background-color: white;
 42             z-index: 10;
 43         }
 44     </style>
 45 </head>
 46 <body>
 47 
 48 <input type="button" value="添加" id="addFunc">
 49 <table border="1px">
 50     <thead>
 51     <tr>
 52         <th>序号</th>
 53         <th>IP</th>
 54         <th>Port</th>
 55         <th>操作</th>
 56     </tr>
 57     </thead>
 58     <tbody>
 59     <tr>
 60         <td>1</td>
 61         <td target="hostname">1.1.1.1</td>
 62         <td target="port">80</td>
 63         <td><input class='modifyFunc' type="button" value="编辑"></td>
 64     </tr>
 65     <tr>
 66         <td>2</td>
 67         <td target="hostname">2.2.2.2</td>
 68         <td target="port">8080</td>
 69         <td><input class='modifyFunc' type="button" value="编辑"></td>
 70     </tr>
 71     <tr>
 72         <td>3</td>
 73         <td target="hostname">3.3.3.3</td>
 74         <td target="port">8443</td>
 75         <td><input class='modifyFunc' type="button" value="编辑"></td>
 76     </tr>
 77     </tbody>
 78 </table>
 79 
 80 <div class="motaiback hide"></div>
 81 <div class="motaiinfo hide">
 82     <p>
 83         <label for="hostname">主机IP:</label>
 84         <input type="text" id="hostname">
 85     </p>
 86     <p>
 87         <label for="port">端口:</label>
 88         <input type="text" id="port">
 89     </p>
 90     <div class='motaibutton'>
 91         <input type="button" value="确定">
 92         <input type="button" value="取消" id="cancelFunc">
 93     </div>
 94 
 95 </div>
 96 
 97 
 98 <script src="jquery-3.1.1.js"></script>
 99 <script>
100     $('#addFunc').click(function () {
101         $('.motaiback,.motaiinfo').removeClass('hide')
102     });
103 
104     $('#cancelFunc').click(function () {
105         $('.motaiback,.motaiinfo').addClass('hide');
106         $(".motaiinfo input[type ='text']").val('');     // 取消时删除模态框中标签的内容
107     });
108     
109     $('.modifyFunc').click(function () {
110         $('.motaiback,.motaiinfo').removeClass('hide');
111         var td_list = $(this).parent().prevAll();
112         td_list.each(function () {
113             if ($(this).attr('target')) {
114                 var attr = $(this).attr('target');
115                 var text = $(this).text();
116 //                var a1 = '.motaiinfo input[id="';   
117 //                var a2 = '"]';
118 //                var temp = a1 + attr + a2;
119 //                $(temp).val(text);    // 这4行,利用下面一行就可以搞定
120                 $('.motaiinfo input[id="'+ attr +'"]').val(text);    // 这里使用字符串拼接,来查找模态对话框的输入框
121             }
122 
123         })
124     });
125 
126 
127 </script>
128 </body>
129 </html>
模态对话框之编辑
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         *{
 8             margin:0;
 9             padding: 0;
10         }
11         .info {
12             width:450px;
13             height:400px;
14             margin:100px auto;
15             border:1px red solid;
16 
17         }
18         .menu {
19             width:150px;
20             height:50px;
21             line-height:50px;
22             display: inline-block;
23             cursor: pointer;
24             text-align: center;
25             margin-right:-6px;
26         }
27         .hide {
28             display: none;
29         }
30         .active {
31             background-color: darkred;
32         }
33         .content {
34             background: darkgray;
35             width:450px;
36             height:300px;
37         }
38     </style>
39 </head>
40 <body>
41 
42 <div class="info">
43     <div class="header">
44         <div class="menu" name="page-1">菜单1</div>
45         <div class="menu" name="page-2">菜单2</div>
46         <div class="menu" name="page-3">菜单3</div>
47     </div>
48     <div class="foot">
49         <div class="content" name="page-1">内容1</div>
50         <div class="content hide" name="page-2">内容2</div>
51         <div class="content hide" name="page-3">内容3</div>
52     </div>
53 </div>
54 
55 <script src="jquery-3.1.1.js"></script>
56 <script>
57     $('.menu').click(function () {
58         $(this).addClass('active').siblings().removeClass('active');
59         var name = $(this).attr('name');
60         $('.foot').children('.content[name="'+ name +'"]').removeClass('hide').siblings().addClass('hide');
61     })
62 </script>
63 
64 
65 </body>
66 </html>
TAB菜单

文档处理

$(..).append()     // 在标签内部,尾部进行追加
$(..).prepend()  // 在标签的内部,首部进行追加
$(..).after()      // 在标签的后面进行追加
$(..).before       // 在标签的前面继续追加

$(..).remove()     // 删除该标签
$(..).empty()      // 情况该标签内容

$(..).clone()      // 复制标签
$(..).index()      // 获取当前标签对于父级标签的索引


// 针对操作的对象不同还有两个方法
$(..).appendTo()     // 把当前标签,追加到某个标签的尾部
$(..).prependTo()  // 把当前标签,追加到某个标签的首部
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <input type="text" id="content">
10 <input type="button" value="添加" id="add">
11 <input type="button" value="删除" id="del">
12 
13 <ul id="ul">
14     <li>1</li>
15     <li>2</li>
16 </ul>
17 <script src="jquery-3.1.1.js"></script>
18 <script>
19     $('#add').click(function () {
20         var test = $('#content').val();
21         var li = $('<li>');
22         li.text(test);
23         li.attr('name','daxin');
24         $('#ul').append(li);
25     });
26     $('#del').click(function () {
27         var test = $('#content').val();
28         $('#ul').children().eq(test).remove()
29     })
30 </script>
31 </body>
32 </html>
添加删除标签

CSS操作

$(..).css('key','value')    // 设置标签的css属性
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .hide {
  8             display: none;
  9         }
 10 
 11         label {
 12             display: inline-block;
 13             width: 70px;
 14             text-align: right;
 15         }
 16 
 17         .motaibutton {
 18             width: 200px;
 19             text-align: right;
 20         }
 21 
 22         .motaiback {
 23             position: fixed;
 24             top: 0;
 25             bottom: 0;
 26             right: 0;
 27             left: 0;
 28             opacity: 0.6;
 29             background-color: #000000;
 30             z-index: 9;
 31         }
 32 
 33         .motaiinfo {
 34             width: 400px;
 35             height: 300px;
 36             position: fixed;
 37             top: 50%;
 38             left: 50%;
 39             margin-top: -150px;
 40             margin-left: -200px;
 41             background-color: white;
 42             z-index: 10;
 43         }
 44     </style>
 45 </head>
 46 <body>
 47 
 48 <input type="button" value="添加" id="addFunc">
 49 <table border="1px" id="tb">
 50     <thead>
 51     <tr>
 52         <th>序号</th>
 53         <th>IP</th>
 54         <th>Port</th>
 55         <th>操作</th>
 56     </tr>
 57     </thead>
 58     <tbody>
 59     <tr>
 60         <td>1</td>
 61         <td target="hostname">1.1.1.1</td>
 62         <td target="port">80</td>
 63         <td><input class='modifyFunc' type="button" value="编辑"></td>
 64     </tr>
 65     <tr>
 66         <td>2</td>
 67         <td target="hostname">2.2.2.2</td>
 68         <td target="port">8080</td>
 69         <td><input class='modifyFunc' type="button" value="编辑"></td>
 70     </tr>
 71     <tr>
 72         <td>3</td>
 73         <td target="hostname">3.3.3.3</td>
 74         <td target="port">8443</td>
 75         <td><input class='modifyFunc' type="button" value="编辑"></td>
 76     </tr>
 77     </tbody>
 78 </table>
 79 
 80 <div class="motaiback hide"></div>
 81 <div class="motaiinfo hide">
 82     <p>
 83         <label for="hostname">主机IP:</label>
 84         <input type="text" id="hostname">
 85     </p>
 86     <p>
 87         <label for="port">端口:</label>
 88         <input type="text" id="port">
 89     </p>
 90     <div class='motaibutton'>
 91         <input type="button" value="确定" id="addHost">
 92         <input type="button" value="取消" id="cancelFunc">
 93     </div>
 94 
 95 </div>
 96 
 97 
 98 <script src="jquery-3.1.1.js"></script>
 99 <script>
100     $('#addFunc').click(function () {
101         $('.motaiback,.motaiinfo').removeClass('hide')
102     });
103 
104     $('#cancelFunc').click(function () {
105         $('.motaiback,.motaiinfo').addClass('hide');
106         $(".motaiinfo input[type ='text']").val('');     // 取消时删除模态框中标签的内容
107     });
108 
109     $('.modifyFunc').click(function () {
110         $('.motaiback,.motaiinfo').removeClass('hide');
111         var td_list = $(this).parent().prevAll();
112         td_list.each(function () {
113             if ($(this).attr('target')) {
114                 var attr = $(this).attr('target');
115                 var text = $(this).text();
116                 $('.motaiinfo input[id="'+ attr +'"]').val(text);    // 这里使用字符串拼接,来查找模态对话框的输入框
117             }
118 
119         })
120     });
121 
122     $('#addHost').click(function () {
123         var td_list = [];
124         $('.motaiinfo').find('[type="text"]').each(function () {
125             var attr = $(this).attr('id');
126             var attr_val = $(this).val();
127             var td = document.createElement('td');
128             $(td).attr('target',attr);
129             $(td).text(attr_val);
130             td_list.push(td)     // 创建好的td标签添加到td_list存储
131         });
132         var tr = document.createElement('tr'); 
133         $(tr).append(td_list);   // td加入到tr中 
134         $('#tb').append(tr);    // tr加入到table中
135         $('.motaiback,.motaiinfo').addClass('hide');
136         $(".motaiinfo input[type ='text']").val('');
137     })
138 
139 
140 
141 </script>
142 </body>
143 </html>
模态对话框之新增
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .main {
 8             width: 600px;
 9             height: 400px;
10             margin: 0 auto;
11             border: 1px solid darkgray;
12         }
13 
14         .content {
15             margin: 20px 0;
16             width: 40px;
17             cursor: pointer;
18             position: relative;
19         }
20 
21     </style>
22 </head>
23 <body>
24 <div class="main">
25     <div class="content">
26         <span class="zan"></span>
27     </div>
28     <div class="content">
29         <span class="zan"></span>
30     </div>
31     <div class="content">
32         <span class="zan"></span>
33     </div>
34     <div class="content">
35         <span class="zan"></span>
36     </div>
37 </div>
38 <script src="jquery-3.1.1.js"></script>
39 <script>
40     $('.zan').click(function () {
41         var span = document.createElement('span');
42         var top = 0;
43         var right = 0;
44         var fontSize = 16;
45         var opacity = 1;
46 
47         $(span).css('position', 'absolute');
48         $(span).css('color', 'green');
49         $(span).css('top', top + 'px');
50         $(span).css('right', right + 'px');
51         $(span).css('fontSize', fontSize + 'px');
52         $(span).css('opacity', opacity);
53         $(span).text('+1');
54         $(this).append(span);
55 
56         var obj = setInterval(function () {    // 利用定时器来调整标签的动态效果
57             top -= 10;
58             right -= 10;
59             fontSize += 5;
60             opacity -= 0.1;
61             console.log(opacity);
62             $(span).css('position', 'absolute');
63             $(span).css('color', 'green');
64             $(span).css('top', top + 'px');
65             $(span).css('right', right + 'px');
66             $(span).css('fontSize', fontSize + 'px');
67             $(span).css('opacity', opacity);
68 
69             if (opacity < 0) {
70                 clearInterval(obj);     // 清除定时器
71                 $(span).remove();    // 删除标签
72             }
73         }, 100)
74 
75 
76     })
77 </script>
78 
79 </body>
80 </html>
点赞之动态+1效 

位置操作

$(..).scrollTop()       // 获取滚轮距离顶部的位置
$(..).scrollLeft()      // 获取滚轮距离左边的位置

$(..).offset()          // 获取标签对象的偏移量,即标签在文档中的位置,以标签的左上角进行定位
$(..).offset().top()    // 获取标签距离顶部的位置
$(..).offset().left()   // 获取标签距离左边的位置

$(..).position()        // 获取当前标签距离其含有position:relative属性的父标签的坐标
$(..).position().left()
$(..).position().top()

// 不加参数表示获取,加参数表示设置

PS:$(window).scrollTop(),表示的是整个页面的滚轮,对象不同,那么作用效果就不同。

高度操作

$(..).height()           // 获取 height 属性的值
$(..).innerHeight()      // 获取 height + border 的值
$(..).outerHeight()      // 获取 height + border + padding 的值
$(..).outerHeight(true)  // 获取 height + border + padding + margin 的值

PS:padding 内边距,margin 外边距 

事件绑定

我们javascript中列举了DOM绑定事件的方式,有三种,下面看一下jQuery绑定事件的方式

$(..).click(function() {} )

$(..).bind('click',function() {} )            // 绑定
$(..).unbind('click',function() {})           // 解绑

$(..).delegate('a','click',function() {} )    // 为标签下的a标签绑定事件
$(..).undelegate('a','click',function() {} )  // 解绑

$(..).on('click',function(){})
$(..).off('click',function(){})

PS:click、bind、delegate绑定事件在内部,其实调用的都是on方法进行绑定的。

注意:这里的delegate,叫做事件委派,比如利用模态对话框进行标签添加的时候,新添加的标签是没有办法按照之前的绑定规则绑定标签的,因为绑定的时候,我们增加的标签还没有在页面上生成,这就需要利用事件委派了,即在点击的时候才进行标签绑定.

// 事件委派方式一
$('ul').delegate('li','click',function () {
            alert($(this).text())
})


// 事件委派方式二
$('ul').on('click','li',function () {
    alert($(this).text());
});       // on标签处理的事件要是目标标签的父标签,这样才能委派
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="jquery-3.1.1.js"></script>
 7 
 8 </head>
 9 <body>
10     <ul>
11         <li>111</li>
12         <li>222</li>
13         <li>333</li>
14     </ul>
15     <button class="button">ADD</button>
16 
17     <script>
18         // 绑定方法
19         $('button').on('click',function () {
20             $('ul').append('<li>444</li>');
21         });  // 通过父标签来添加子标签
22 
23 
24 //    $('ul').on('click','li',function () {
25 //        alert($(this).text());
26 //    });  // on标签处理的事件要是目标标签的父标签
27         $('ul').delegate('li','click',function () {
28             alert($(this).text())
29         })
30 
31     </script>
32 </body>
33 </html>
事件委派

事件类型

jQuery事件对DOM事件继续了封装,去掉了DOM事件中的on关键字。

blur([[data],fn])        // 当元素失去焦点时触发 blur 事件。
change([[data],fn])      // 当元素的值发生改变时,会发生 change 事件。
click([[data],fn])       // 当元素被点击时,触发 click 事件。
dblclick([[data],fn])    // 当元素被双击时,触发 click 事件。
focus([[data],fn])       // 当元素获得焦点时,触发 focus 事件。
focusin([data],fn)       // 当元素获得焦点时,触发 focusin 事件。跟focus事件区别在于,他可以在父元素上检测子元素获取焦点的情况。
focusout([data],fn)      // 当元素失去焦点时触发 focusout 事件。跟blur事件区别在于,他可以在父元素上检测子元素失去焦点的情况。
keydown([[data],fn])     // 当键盘或按钮被按下时,发生 keydown 事件。
keypress([[data],fn])    // 当键盘或按钮被按下时,发生 keypress 事件。
keyup([[data],fn])       // 当按钮被松开时,发生 keyup 事件。它发生在当前获得焦点的元素上。
mousedown([[data],fn])   // 当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。
mouseenter([[data],fn])  // 当鼠标指针穿过元素时,会发生 mouseenter 事件。该事件大多数时候会与mouseleave 事件一起使用。
mouseleave([[data],fn])  // 当鼠标指针离开元素时,会发生 mouseleave 事件。该事件大多数时候会与mouseenter 事件一起使用。
mousemove([[data],fn])   // 当鼠标指针在指定的元素中移动时,就会发生 mousemove 事件。
mouseout([[data],fn])    // 当鼠标指针从元素上移开时,发生 mouseout 事件。该事件大多数时候会与 mouseover 事件一起使用。
mouseover([[data],fn])   // 当鼠标指针位于元素上方时,会发生 mouseover 事件。该事件大多数时候会与 mouseout 事件一起使用。
mouseup([[data],fn])     // 当在元素上放松鼠标按钮时,会发生 mouseup 事件。
resize([[data],fn])      // 当调整浏览器窗口的大小时,发生 resize 事件。
scroll([[data],fn])      // 当用户滚动指定的元素时,会发生 scroll 事件。
select([[data],fn])      // 当 textarea 或文本类型的 input 元素中的文本被选择时,会发生 select 事件。
submit([[data],fn])      // 当提交表单时,会发生 submit 事件。
1 $(window).keydown(function(event){
2   switch(event.keyCode) {
3     // ...
4     // 不同的按键可以做不同的事情
5     // 不同的浏览器的keycode不同
6     // 更多详细信息:     http://unixpapa.com/js/key.html
7     // 常用keyCode: 空格 32   Enter 13   ESC 27
8   }
9 });
keydown事件

PS:更多的用法请参考:http://jquery.cuishifeng.cn/index.html

阻止默认事件

比如a标签,我们都知道当我们点击A标签的时候,它会默认触发一个跳转动作,那我们是否可以再给它绑定一个其他的事件?答案当然是可以的。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="http://www.baidu.com" id="a">百度</a>
<script src="jquery-3.1.1.js"></script>
<script>
    $('#a').click(function () {
        alert(123)
    })
</script>
</body>

</html>

通过上面的例子可以看出,我们绑定的事件会先于默认事件发生,那么我们能否阻止默认事件的产生呢?答案当然也是可以的,并且很简单,只需要在事件绑定的函数中return false即可

$('#a').click(function () {
    alert(123)
    return false    // 返回false即可抑制默认事件,true或者不返回,就表示 不抑制
})

利用阻止默认事件来进行form表单的验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error {
            color:red;
        }
    </style>
</head>
<body>
<form action="http://www.baidu.com" method="post" id="form">
    <div class="item">
        <label for="name">用户名:</label>
        <input type="text" id="name">
    </div>
    <div class="item">
        <label for="password">密码:</label>
        <input type="password" id="password">
    </div>
    <input type="submit" value="登陆" id="upload">
</form>

<script src="jquery-3.2.1.js"></script>
<script>
    $('#upload').click(function () {
        var flag = true;    // 创建反回标识符
        $('#form').find('input[type="text"],input[type="password"]').each(function () {    // 查找到需要验证的标签
            $(this).next().remove();    // 首先移除错误提示,不然二次提交后,错误提示会叠加
            var val = $(this).val();    // 获取输入框用户输入的数据
            if (val.length <= 0 ) {     // 如果长度为0,表示异常
                var span = document.createElement('span');   // 创建错误提示标签
                $(span).text('不能为空');
                $(span).addClass('error');
                $(this).after(span);
                flag = false;    // 修改返回标识符
            }
//            return false;    // 在这里return false只会终止循环。
        });
        return flag;  // 阻止默认事件
    })
</script>
</body>
</html>

扩展

页面加载自执行

正常情况下,我们加载页面的顺序为,等待页面资源全部加载完毕后,继续加载我们的js代码,但是如果我只是某一个图片(比方)有网络延迟,那么不应该阻止js代码的加载。 这里就需要使用特殊的js加载方式

$(function (){

  // jscode

})();

在内部编写的js代码会在HTML页面框架加载完毕后,直接就开始加载js代码了。

// 建议页面中的js代码使用如下方式绑定

<script src='jquery.1.1.13.js'></script>
<script>
    $(function (){
        
        var ele = document.getElementById('..')
        ele.onclick = function () {
              // jscode
        }
        
    .... ....
    })()
</script>

PS:当然在jQuery原码中,我们看到自动执行函数,还传递了window变量,这是因为,jQuery在内部封装了很多函数,因为函数作用域的问题,只能在内部调用,如果想要在外部调用,那么可以把方法绑定到window对象上,这样,我们在程序中调用的$,或者 jquery 其实调用的就是绑定在 window上的jQuery提供的函数。

jQuery扩展

根据上面的知识,jquery提供的功能函数其实有两类:

$(..).css()    // 选择器对象的方法
$.ajax()       // jQuery对象的方法
扩展jQuery对象的方法

jQuery专门提供了对应的方法:$.extend()

 $.extend({
        'daxin':function () {
            return 'daxin,you are so handsome';
        }
});


// 参数为字典,key是方法的名称,value是函数体

PS:通过上述方法就给jQuery对象绑定了我们自定义的方法,另外function还可以接收参数,只需要在括号中写入形参即可。

扩展选择器对象的方法 

 jQuery也提供了专门的方法:$.fn.extend()

$.fn.extend({
    'daxin':function () {
        return 'you are so handsome'
    }
});

var info = $('#abc').daxin();
alert(info);

// 通过标签选择器对象调用扩展的方法

PS:当我们把扩展函数写在一个文件中时,为了防止方法名和变量冲突被覆盖的问题,一般会在文件中使用自执行函数进行包裹。

操作cookies

  在javascript中我们可以利用DOM对象来获取cookie,但是设置起来比较麻烦,使用jquery的cookies插件可以方便的进行cookie的修改,插入等。cookies插件独立于jquery需要下载,及引入。

<script src='js/jquery.cookie.js'></script>    # 引入jquery.cookie

通过jquery.cookie插件操作cookies

$.cookie('user')               # 获取cookie中key为user的值
$.cookie('user','dachenzi')    # 设置cookie中key为user的值为dachenzi

cookie拥有众多参数,用于设置过期时间等

  • expires:cookie过期时间
  • path:cookie生效路径
  • domain:cookie生效域名
  • secure:https传输

添加参数时,传递参数字典即可

$.cookie('user','dachenzi',{'expires':10,...})
posted @ 2017-08-14 10:52 Dahlhin 阅读( ...) 评论( ...)   编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值