jQuery攻略

1、簡介javascript

1.介紹
  jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype以後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是「write Less,Do More」,
即倡導寫更少的代碼,作更多的事情。它封裝JavaScript經常使用的功能代碼,提供一種簡便的JavaScript設計模式,優化HTML文檔操做、事件處理、動畫設計和Ajax交互。css

 

2.優點html

  • 一款輕量級的JS框架。jQuery核心js文件才幾十kb,不會影響頁面加載速度。
  • 豐富的DOM選擇器,jQuery的選擇器用起來很方便,好比要找到某個DOM對象的相鄰元素,JS可能要寫好幾行代碼,而jQuery一行代碼就搞定了,再好比要將一個表格的隔行變色,jQuery也是一行代碼搞定。
  • 鏈式表達式。jQuery的鏈式操做能夠把多個操做寫在一行代碼裏,更加簡潔。
  • 事件、樣式、動畫支持。jQuery還簡化了js操做css的代碼,而且代碼的可讀性也比js要強。
  • Ajax操做支持。jQuery簡化了AJAX操做,後端只需返回一個JSON格式的字符串就能完成與前端的通訊。
  • 跨瀏覽器兼容。jQuery基本兼容瞭如今主流的瀏覽器,不用再爲瀏覽器的兼容問題而傷透腦筋。
  • 插件擴展開發。jQuery有着豐富的第三方的插件,例如:樹形菜單、日期控件、圖片切換插件、彈出窗口等等基本前端頁面上的組件都有對應插件,而且用jQuery插件作出來的效果很炫,而且能夠根據本身須要去改寫和封裝插件,簡單實用。

3.jQuery內容前端

  • 選擇器
  • 篩選器
  • 樣式操做
  • 文本操做
  • 屬性操做
  • 文檔處理
  • 事件
  • 動畫效果
  • 插件
  • each、data、Ajax

4.jQuery對象
  jQuery對象就是經過jQuery包裝DOM對象後產生的對象。jQuery對象是 jQuery獨有的。若是一個對象是 jQuery對象,那麼它就可使用jQuery裏的方法:例如$(「#i1」).html()。

  $("#i1").html()的意思是:獲取id值爲 i1的元素的html代碼。其中 html()是jQuery裏的方法。

  至關於: document.getElementById("i1").innerHTML;

  雖然 jQuery對象是包裝 DOM對象後產生的,可是 jQuery對象沒法使用 DOM對象的任何方法,同理 DOM對象也沒不能使用 jQuery裏的方法。

  一個約定,咱們在聲明一個jQuery對象變量的時候在變量名前面加上$:java

var $variable = jQuery對像
var variable = DOM對象
$variable[0]//jQuery對象轉成DOM對象

  拿上面那個例子舉例,jQuery對象和DOM對象的使用:python

$("#i1").html();//jQuery對象可使用jQuery的方法
$("#i1")[0].innerHTML;// DOM對象使用DOM的方法

  

2、查找元素
1.選擇器
(1)基本選擇器jquery

id選擇器:
$("#id")

標籤選擇器:
$("tagName")

class選擇器:
$(".className")

配合使用:
$("div.c1")  // 找到有c1 class類的div標籤

全部元素選擇器:
$("*")

組合選擇器:
$("#id, .className, tagName")

  

(2)層級選擇器web

$("x y"); // x的全部後代y(子子孫孫)
$("x > y"); // x的全部兒子y(兒子)
$("x + y"); // 找到全部緊挨在x後面的y
$("x ~ y"); // x以後全部的兄弟y

 

(3)內容選擇器後端

:first // 第一個
:last // 最後一個
:eq(index)// 索引等於index的那個元素
:even // 匹配全部索引值爲偶數的元素,從 0 開始計數
:odd // 匹配全部索引值爲奇數的元素,從 0 開始計數
:gt(index)// 匹配全部大於給定索引值的元素
:lt(index)// 匹配全部小於給定索引值的元素
:not(元素選擇器)// 移除全部知足not條件的標籤
:has(元素選擇器)// 選取全部包含一個或多個標籤在其內的標籤(指的是從後代元素找)

  

(4)表單選擇器設計模式

$(":input") //匹配全部 input, textarea, select 和 button 元素
$(":text") //全部的單行文本框
$(":password") //全部密碼框
$(":radio") //全部單選按鈕
$(":checkbox") //全部複選框
$(":submit") //全部提交按鈕
$(":reset") //全部重置按鈕
$(":button") //全部button按鈕
$(":file") //全部文件域

$("input:checked")    //全部選中的元素
$("select option:selected")    //select中全部選中的option元素
表單對象屬性:
:enabled
:disabled
:checked
:selected

  

exp:找到可用的input標籤
<form>
  <input name="email" disabled="disabled" />
  <input name="id" />
</form>
$("input:enabled")  // 找到可用的input標籤


exp:找到被選中的option:
<select id="s1">
  <option value="beijing">北京市</option>
  <option value="shanghai">上海市</option>
  <option selected value="guangzhou">廣州市</option>
  <option value="shenzhen">深圳市</option>
</select>

$(":selected")  // 找到全部被選中的option
示例

 

(5)屬性選擇器

[attribute]
[attribute=value]// 屬性等於
[attribute!=value]// 屬性不等於

  

exp:
<input type="text">
<input type="password">
<input type="checkbox">
$("input[type='checkbox']");// 取到checkbox類型的input標籤
$("input[type!='text']");// 取到類型不是text的input標籤
示例

 

2.篩選器

(1)基本篩選器

$("#id").eq(0) //當前操做中第N個jQuery對象,相似索引
$("#id").first() //第一個元素
$("#id").last() //最後一個元素
$(this).hasClass("test") //元素是否含有某個特定的類,返回布爾值
$("#id").has('ul') //包含特定後代的元素

  

(2)下一個元素

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")

  

(3)上一個元素

$("#id").prev()
$("#id").prevAll()
$("#id").prevUntil("#i2")

  

(4)父親元素

$("#id").parent()
$("#id").parents() // 查找當前元素的全部的父輩元素
$("#id").parentsUntil() // 查找當前元素的全部的父輩元素,直到遇到匹配的那個元素爲止。

  

(5)兒子和兄弟元素

$("#id").children();// 兒子們
$("#id").siblings();// 兄弟們

  

(6)查找 搜索全部與指定表達式匹配的元素。這個函數是找出正在處理的元素的後代元素的好方法。

$("div").find("p")

等價於$("div p")

  

(7)篩選 篩選出與指定表達式匹配的元素集合。這個方法用於縮小匹配的範圍。用逗號分隔多個表達式。

$("div").filter(".c1") // 從結果集中過濾出有c1樣式類的

等價於 $("div.c1")

  

3、操做標籤
1.屬性操做
(1)用於ID等或自定義屬性:

attr(attrName)// 返回第一個匹配元素的屬性值
attr(attrName, attrValue)// 爲全部匹配元素設置一個屬性值
attr({k1: v1, k2:v2})// 爲全部匹配元素設置多個屬性值
removeAttr()// 從每個匹配的元素中刪除一個屬性


(2)用於checkbox和radio

prop() // 獲取屬性
removeProp() // 移除屬性

  

<input type="checkbox" value="1">
<input type="radio" value="2">
<script>
  $(":checkbox[value='1']").prop("checked", true);
  $(":radio[value='2']").prop("checked", true);
</script>
prop

 

prop和attr的區別:

attr全稱attribute(屬性)

prop全稱property(屬性)

雖然都是屬性,但他們所指的屬性並不相同,attr所指的屬性是HTML標籤屬性,而prop所指的是DOM對象屬性,能夠認爲attr是顯式的,而prop是隱式的。

舉個例子:

<input type="checkbox" id="i1" value="1">
針對上面的代碼,

$("#i1").attr("checked")  // undefined
$("#i1").prop("checked")  // false
能夠看到attr獲取一個標籤內沒有的東西會獲得undefined,而prop獲取的是這個DOM對象的屬性,所以checked爲false。

若是換成下面的代碼:

<input type="checkbox" checked id="i1" value="1">
再執行:

$("#i1").attr("checked")   // checked
$("#i1").prop("checked")  // true
這已經能夠證實attr的侷限性,它的做用範圍只限於HTML標籤內的屬性,而prop獲取的是這個DOM對象的屬性,選中返回true,沒選中返回false。

接下來再看一下針對自定義屬性,attr和prop又有什麼區別:

<input type="checkbox" checked id="i1" value="1" me="自定義屬性">
執行如下代碼:

$("#i1").attr("me")   // "自定義屬性"
$("#i1").prop("me")  // undefined
能夠看到prop不支持獲取標籤的自定義屬性。

總結一下:

對於標籤上有的能看到的屬性和自定義屬性都用attr
對於返回布爾值的好比checkbox、radio和option的是否被選中都用prop。
attr和prop區別

 

2.CSS類操做

addClass();// 添加指定的CSS類名。
removeClass();// 移除指定的CSS類名。
toggleClass();// 切換CSS類名,若是有就移除,若是沒有就添加。
hasClass();// 判斷樣式存不存在

  

<script>
    $("p").click(function () {
        // $(this).css("color","red");
        // $(this).css("font-size","30px");
        $(this).css({"color":"red","font-size":"30px"})
    })
</script>

 

3.HTML代碼和文本值

HTML代碼:
html()// 取得第一個匹配元素的html內容
html(val)// 設置全部匹配元素的html內容

文本值:
text()// 取得全部匹配元素的內容
text(val)// 設置全部匹配元素的內容

值:
val()// 取得第一個匹配元素的當前值
val(val)// 設置全部匹配元素的值
val([val1, val2])// 設置多選的checkbox、多選select的值

  

$('p').html();               //返回p元素的html內容
$("p").html("Hello <b>nick</b>!");  //設置p元素的html內容
$('p').text();               //返回p元素的文本內容
$("p").text("nick");           //設置p元素的文本內容
$("input").val();             //獲取文本框中的值
$("input").val("nick");          //設置文本框中的內容

  

<input type="checkbox" value="basketball" name="hobby">籃球
<input type="checkbox" value="football" name="hobby">足球

<select multiple id="s1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

設置值:

$("[name='hobby']").val(['basketball', 'football']);
$("#s1").val(["1", "2"])

  

4.位置操做

  • offset()// 獲取匹配元素在當前窗口的相對偏移或設置元素位置
  • position()// 獲取匹配元素相對父元素的偏移
  • scrollTop()// 獲取匹配元素相對滾動條頂部的偏移
  • scrollLeft()// 獲取匹配元素相對滾動條左側的偏移
<!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>位置相關示例之返回頂部</title>

  <!--<link href="https://cdn.bootcss.com/normalize/8.0.1/normalize.css" rel="stylesheet">-->
  <style>
    .c1 {
      width: 100px;
      height: 200px;
      background-color: red;
    }

    .c2 {
      height: 50px;
      width: 50px;

      position: fixed;
      bottom: 15px;
      right: 15px;
      background-color: #2b669a;
    }
    .hide {
      display: none;
    }
    .c3 {
      height: 100px;
    }
  </style>

</head>
<body>
<button id="b1" class="btn btn-default">點我</button>
<div class="c1"></div>
<div class="c3">1</div>
<div class="c3">2</div>
<div class="c3">3</div>
<div class="c3">4</div>
<div class="c3">5</div>
<div class="c3">6</div>
<div class="c3">7</div>
<div class="c3">8</div>
<div class="c3">9</div>
<div class="c3">10</div>
<div class="c3">11</div>
<div class="c3">12</div>
<div class="c3">13</div>
<div class="c3">14</div>
<div class="c3">15</div>
<div class="c3">16</div>
<div class="c3">17</div>
<div class="c3">18</div>

<button id="b2" class="btn btn-default c2 hide">返回頂部</button>
<script src="jquery-3.3.1.min.js"></script>
<script>
  $("#b1").click(function () {
    $(".c1").offset({left: 200, top:200});
  });

  $(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
      $("#b2").removeClass("hide");
    }else {
      $("#b2").addClass("hide");
    }
  });
  $("#b2").click(function () {
    $(window).scrollTop(0);
  })
</script>
</body>
</html>
返回頂部

 

5.尺寸

height()    //獲取元素的高度
width()     //獲取元素的寬度
innerHeight()   //獲取元素內部區域高度(包括補白、不包括邊框)
innerWidth()    //獲取元素內部區域寬度(包括補白、不包括邊框)
outerHeight()    //匹配元素外部高度(默認包括補白和邊框)
outerWidth()    //匹配元素外部寬度(默認包括補白和邊框)
outerHeight(true)    //爲true時包括邊距

  

4、文檔操做

添加到指定元素內部的後面
$(A).append(B)// 把B追加到A
$(A).appendTo(B)// 把A追加到B

添加到指定元素內部的前面
$(A).prepend(B)// 把B前置到A
$(A).prependTo(B)// 把A前置到B

添加到指定元素外部的後面
$(A).after(B)// 把B放到A的後面
$(A).insertAfter(B)// 把A放到B的後面

添加到指定元素外部的前面
$(A).before(B)// 把B放到A的前面
$(A).insertBefore(B)// 把A放到B的前面

移除和清空元素
remove()// 從DOM中刪除全部匹配的元素。
empty()// 刪除匹配的元素集合中全部的子節點。

克隆
clone()// 參數

  

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>增長元素</title>
</head>
<body>


<ul id="ul">
    <li id="li1">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<script src="jquery-3.3.1.min.js"></script>
<script>
    // var liEle1 = document.createElement('li');
    // liEle1.innerText = "在最後增長的li標籤";
    //在ul內部最後增長標籤
    // $("#ul").append(liEle1);

    // $(liEle1).appendTo($("#ul"));
    //
    // var liEle2 = document.createElement('li');
    // liEle2.innerText = "在最前面增長的li標籤";
    //在ul內部最前面增長標籤
    // $("#ul").prepend(liEle2);
    // $(liEle2).prependTo($("#ul"))

    // var liEle3 = document.createElement('li');
    // liEle3.innerText = "在id爲li1標籤後面增長li標籤";
    //同級增長
    // // $("#li1").after(liEle3)
    // $(liEle3).insertAfter($("#li1"));


    var liEle4 = document.createElement('li');
    liEle4.innerText = "在id爲li1標籤前面增長li標籤";
    //同級增長
    // $("#li1").before(liEle4);
    $(liEle4).insertBefore($('#li1'));

    // $("#ul").remove(); //刪除ul標籤
    // $("#ul").empty();   //狀況ul標籤下的標籤
</script>
</body>
</html>
文檔操做

 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>02點擊在表格最後增長一條記錄</title>
</head>
<body>
<table border="1px">
    <thead>
    <tr>
        <th>序號</th>
        <th>姓名</th>
        <th>年齡</th>
        <th>操做</th>
    </tr>
    </thead>
    <tbody id="t1">
    <tr>
        <td>1</td>
        <td>alina</td>
        <td>18</td>
        <td><button class="del">刪除</button></td>
    </tr>
    <tr>
        <td>2</td>
        <td>felix</td>
        <td>20</td>
        <td><button class="del">刪除</button></td>
    </tr>
    </tbody>
</table>
<button id="b1">增長一行數據</button>
<script src="jquery-3.3.1.min.js"></script>

<script>
    // 增長一行數據
    $("#b1").click(function () {
        var trEle = document.createElement("tr");
        $(trEle).html("<td>3</td><td>lisa</td><td>6</td><td><button class='del'>刪除</button></td>");
        $("#t1").append($(trEle))
    });

    // 刪除一行數據
    $(`.del`).click(function () {
        console.log('ok');
        $(this).parent().parent().remove();
    });

</script>
</body>
</html>
新增一條記錄

 

5、事件

1.事件

$("p").click();   //單擊事件
$("p").dblclick(); //雙擊事件
$("input[type=text]").focus() //元素得到焦點時,觸發 focus 事件
$("input[type=text]").blur() //元素失去焦點時,觸發 blur事件
$("button").mousedown()//當按下鼠標時觸發事件
$("button").mouseup() //元素上放鬆鼠標按鈕時觸發事件
$("p").mousemove() //當鼠標指針在指定的元素中移動時觸發事件
$("p").mouseover() //當鼠標指針位於元素上方時觸發事件
$("p").mouseout()  //當鼠標指針從元素上移開時觸發事件
$(window).keydown() //當鍵盤或按鈕被按下時觸發事件
$(window).keypress() //當鍵盤或按鈕被按下時觸發事件,每輸入一個字符都觸發一次
$("input").keyup() //當按鈕被鬆開時觸發事件
$(window).scroll() //當用戶滾動時觸發事件
$(window).resize() //當調整瀏覽器窗口的大小時觸發事件
$("input[type='text']").change() //當元素的值發生改變時觸發事件
$("input").select() //當input 元素中的文本被選擇時觸發事件
$("form").submit() //當提交表單時觸發事件
$(window).unload() //用戶離開頁面時

  

2.頁面載入
  當DOM載入就緒能夠查詢及操縱時綁定一個要執行的函數,這是事件模塊中最重要的一個函數,由於它能夠極大地提升web應用程序的響應速度。
能夠在同一個頁面中無限次地使用$(document).ready()事件。其中註冊的函數會按照(代碼中的)前後順序依次執行。

ready(fn)

$(document).ready(function(){
// 在這裏寫你的代碼...
});

//簡寫
$(function($) {
do something...
});

  

Display a paragraph's text in an alert when it is clicked:

$("p").on("click", function(){
alert( $(this).text() );
});
Pass data to the event handler, which is specified here by name:

function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)
Cancel a form submit action and prevent the event from bubbling up by returning false:

$("form").on("submit", false)
Cancel only the default action by using .preventDefault().

$("form").on("submit", function(event) {
  event.preventDefault();
});
Stop submit events from bubbling without preventing form submit, using .stopPropagation().

$("form").on("submit", function(event) {
  event.stopPropagation();
});
示例

 

3.事件綁定
(1)在選擇元素上綁定一個或多個事件的事件處理函數--- .on()

.on(events,[selector],[data],fn)

說明:
events:一個或多個用空格分隔的事件類型和可選的命名空間,如"click"或"keydown.myPlugin" 。
selector:一個選擇器字符串用於過濾器的觸發事件的選擇器元素的後代。若是選擇的< null或省略,當它到達選定的元素,事件老是觸發。
data:當一個事件被觸發時要傳遞event.data給事件處理函數。
fn:該事件被觸發時執行的函數。 false 值也能夠作一個函數的簡寫,返回false。

  

(2)爲每個匹配元素的特定事件(像click)綁定一個一次性的事件處理函數--- .one()

one(type,[data],fn)
type:添加到元素的一個或多個事件。由空格分隔多個事件。必須是有效的事件。
data:將要傳遞給事件處理函數的數據映射
fn:每當事件觸發時執行的函數。

  

4.事件移除--- .off()
在選擇元素上移除一個或多個事件的事件處理函數。

.off(events,[selector],[fn])
events:一個或多個空格分隔的事件類型和可選的命名空間,或僅僅是命名空間,好比"click", "keydown.myPlugin", 或者 ".myPlugin".
selector:一個最初傳遞到.on()事件處理程序附加的選擇器。
fn:事件處理程序函數之前附加事件上,或特殊值false.

 

Remove all event handlers from all paragraphs:

$("p").off()
Remove all delegated click handlers from all paragraphs:

$("p").off( "click", "**" )
Remove just one previously bound handler by passing it as the third argument:

var foo = function () {
// code to handle some kind of event
};

// ... now foo will be called when paragraphs are clicked ...
$("body").on("click", "p", foo);


// ... foo will no longer be called.
$("body").off("click", "p", foo);
Unbind all delegated event handlers by their namespace:

var validate = function () {
// code to validate form entries
};

// delegate events under the ".validator" namespace
$("form").on("click.validator", "button", validate);

$("form").on("keypress.validator", "input[type='text']", validate);

// remove event handlers in the ".validator" namespace

$("form").off(".validator");
示例

 

5.阻止後續事件執行

  • return false; // 常見阻止表單提交等
  • e.preventDefault();
$("p").click(function(event){  
 alert(event.type); //"click"  
}); 

(evnet object)屬性方法:
event.pageX   //事件發生時,鼠標距離網頁左上角的水平距離
event.pageY   //事件發生時,鼠標距離網頁左上角的垂直距離
event.type   //事件的類型
event.which   //按下了哪個鍵
event.data   //在事件對象上綁定數據,而後傳入事件處理函數
event.target  //事件針對的網頁元素
event.preventDefault()  //阻止事件的默認行爲(好比點擊連接,會自動打開新頁面)
event.stopPropagation()  //中止事件向上層元素冒泡
其餘Event對象

 

6.事件委託
  事件委託是經過事件冒泡的原理,利用父標籤去捕獲子標籤的事件。

$("table").on("click", ".delete", function () {
// 刪除按鈕綁定的事件
})

  

 6、效果

基本

$("p").show()        //顯示隱藏的匹配元素
$("p").show("slow");    //參數表示速度,("slow","normal","fast"),也可爲900毫秒
$("p").hide()        //隱藏顯示的元素
$("p").toggle();      //切換 顯示/隱藏

滑動

$("p").slideDown("900");    //用900毫秒時間將段落滑下
$("p").slideUp("900");     //用900毫秒時間將段落滑上
$("p").slideToggle("900");  //用900毫秒時間將段落滑上,滑下

淡入淡出

$("p").fadeIn("900");        //用900毫秒時間將段落淡入
$("p").fadeOut("900");       //用900毫秒時間將段落淡出
$("p").fadeToggle("900");     //用900毫秒時間將段落淡入,淡出
$("p").fadeTo("slow", 0.6);    //用900毫秒時間將段落的透明度調整到0.6

 

7、其它

1.遍歷

jQuery.each(collection, callback(indexInArray, valueOfElement)):

描述:一個通用的迭代函數,它能夠用來無縫迭代對象和數組。數組和相似數組的對象經過一個長度屬性(如一個函數的參數對象)來迭代數字索引,從0到length - 1。其餘對象經過其屬性名進行迭代。

.each(function(index, Element))  遍歷一個jQuery對象,爲每一個匹配元素執行一個函數。

.each() 方法用來迭代jQuery對象中的每個DOM元素。每次回調函數執行時,會傳遞當前循環次數做爲參數(從0開始計數)。因爲回調函數是在當前DOM元素爲上下文的語境中觸發的,因此關鍵字 this 老是指向這個元素。

// 爲每個li標籤添加foo
$("li").each(function(){
  $(this).addClass("c1");
});

注意: jQuery的方法返回一個jQuery對象,遍歷jQuery集合中的元素 - 被稱爲隱式迭代的過程。當這種狀況發生時,它一般不須要顯式地循環的 .each()方法:

也就是說,上面的例子沒有必要使用each()方法,直接像下面這樣寫就能夠了:

$("li").addClass("c1");  // 對全部標籤作統一操做

注意:

在遍歷過程當中可使用 return false提早結束each循環。

終止each循環

return false

 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>10each循環</title>
</head>
<body>
<div>111</div>
<div>222</div>
<div>333</div>
<div>444</div>
<div>555</div>
<div>666</div>

<script src="jquery-3.3.1.min.js"></script>
<script>
    var $divEles = $("div");
    // for (var i=0;i<$divEles.length;i++) {
    //     console.log($divEles[i].innerText)
    // }

    // 循環全部div標籤
    $divEles.each(function () {
        console.log(this.innerText)
    });

    // // 循環數組
    // var lst = [11,22,33,44,55]
    // $.each(lst,function (index,value) {
    //     console.log(index + ":" + value)
    // })

    // 循環數組
    var lst = [11,22,33,44,55]
    $.each(lst,function (index,value) {
        if (value===33) {
            // return false 相似於break 退出當前循環

            //退出當前這一次循環 相似於continue
            return;
        }
        console.log(index + ":" + value);
    })

</script>

</body>
</html>
each示例

 

2.數據緩存

  在匹配的元素集合中的全部元素上存儲任意相關數據或返回匹配的元素集合中的第一個元素的給定名稱的數據存儲的值。

.data(key, value):  在匹配的元素上存儲任意相關數據。

$("div").data("blah");  // undefined
$("div").data("blah", "hello");  // blah設置爲hello
$("div").data("blah");  // hello
$("div").data("blah", 86);  // 設置爲86
$("div").data("blah");  //  86
$("div").removeData("blah");  //移除blah
$("div").data("blah");  // undefined

  

.removeData(key):  移除存放在元素上的數據,不加key參數表示移除全部保存的數據。

$("div").removeData("k");  //移除元素上存放k對應的數據

  

3.插件

jQuery.extend(object)  jQuery的命名空間下添加新的功能。多用於插件開發者向 jQuery 中添加新函數時使用。

<script>
jQuery.extend({
  min:function(a, b){return a < b ? a : b;},
  max:function(a, b){return a > b ? a : b;}
});
jQuery.min(2,3);// => 2
jQuery.max(4,5);// => 5
</script>

  

jQuery.fn.extend(object)  一個對象的內容合併到jQuery的原型,以提供新的jQuery實例方法。

<script>
  jQuery.fn.extend({
    check:function(){
      return this.each(function(){this.checked =true;});
    },
    uncheck:function(){
      return this.each(function(){this.checked =false;});
    }
  });
// jQuery對象可使用新添加的check()方法了。
$("input[type='checkbox']").check();
</script>

  

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>插件</title>
</head>
<body>
<div class="c1">插件</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
    $.fn.extend({
            "myprint": function () {
                console.log("加油!努力學好JS!")
            }
        }
    );

    $.extend({
            "myconsole": function () {
                console.log("加油!努力學好JS!")
            }
        }
    )
</script>

$(".c1").myprint();
//加油!努力學好JS!
$.myconsole();
</body>
</html>
示例

 

 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登陸校驗完整版</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
<form id="f1">
    <p>
        <label>用戶名:
            <input class="need" name="username" type="text">
            <span class="error"></span>
        </label>
    </p>
    <p>
        <label>密碼:
            <input class="need" name="password" type="password">
            <span class="error"></span>
        </label>
    </p>

    <p>愛好:
        <label>籃球
            <input name="hobby" value="basketball" type="checkbox">
        </label>
        <label>足球
            <input name="hobby" value="football" type="checkbox">
        </label>
        <label>雙色球
            <input name="hobby" value="doublecolorball" type="checkbox">
        </label>
    </p>

    <p>性別:
        <label><input name="gender" value="1" type="radio">
        </label>
        <label><input name="gender" value="0" type="radio">
        </label>
        <label>保密
            <input name="gender" value="2" type="radio">
        </label>
    </p>

    <p>
        <label for="s1">從哪兒來:</label>
        <select name="from" id="s1">
            <option value="010">北京</option>
            <option value="021">上海</option>
            <option value="020">廣州</option>
        </select>
    </p>
    <p>
        <label for="s2">從哪兒來:</label>
        <select name="from" id="s2" multiple>
            <option value="010">北京</option>
            <option value="021">上海</option>
            <option value="020">廣州</option>
            <option value="0755">深圳</option>
        </select>
    </p>
    <p>
        <label for="t1">我的簡介:</label>
        <textarea name="memo" id="t1" cols="30" rows="10">

        </textarea>
    </p>
    <p>
        <input id="b1" type="submit" value="登陸">
        <input id="cancel" type="button" value="取消">
    </p>
</form>
<script src="jquery-3.3.1.min.js"></script>
<script>
    // 點擊登陸按鈕驗證用戶名和密碼爲不爲空
    // 爲空就在對應的input標籤下面顯示一個錯誤提示信息

    // 1. 給登陸按鈕綁定點擊事件
    // 2. 點擊事件要作的事兒
    // 2.1 找到input標籤--> 取值 --> 判斷爲不爲空 --> .length爲不爲0
    // 2.2 若是不爲空,則什麼都不作
    // 2.2 若是爲空,要作幾件事兒
    // 2.2.1 在當前這個input標籤的下面 添加一個新的標籤,內容爲xx不能爲空

    $("#b1").click(function () {
        var $needEles = $(".need");
        // 定義一個標誌位
        var flag = true;
        for (var i = 0; i < $needEles.length; i++) {
            // 若是有錯誤
            if ($($needEles[i]).val().trim().length === 0) {
                var labelName = $($needEles[i]).parent().text().trim().slice(0, -1);
                console.log($($needEles[i]).next().text().length);
                if ($($needEles[i]).next().text().length === 0) {
                    $($needEles[i]).next().text(labelName + "不能爲空!");
                }

                // 將標誌位置爲false
                flag = false;
                break;
            }
        }
        return flag;
    })

</script>
</body>
</html>
登陸校驗
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>鍵盤相關事件</title>

</head>
<body>

<table border="1" id="t1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>愛好</th>
        <th>操做</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>小強</td>
        <td>吃冰激凌</td>
        <td>
            <select>
                <option value="0">下線</option>
                <option value="1">上線</option>
                <option value="2">離線</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <select>
                <option value="0">下線</option>
                <option value="1">上線</option>
                <option value="2">離線</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <select>
                <option value="0">下線</option>
                <option value="1">上線</option>
                <option value="2">離線</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <select>
                <option value="0">下線</option>
                <option value="1">上線</option>
                <option value="2">離線</option>
            </select>
        </td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>二哥</td>
        <td>Girl</td>
        <td>
            <select>
                <option value="0">下線</option>
                <option value="1">上線</option>
                <option value="2">離線</option>
            </select>
        </td>
    </tr>

    </tbody>
</table>
<p>提示:按下Ctrl鍵可批量操做狀態</p>
<script src="jquery-3.3.1.min.js"></script>
<script>
    // 確保綁定事件的時候DOM樹是生成好的
    $(document).ready(function () {
        var mode = false;
        var $bodyEle = $("body");
        // 給文檔綁定 監聽鍵盤按鍵被按下去的事件
        $bodyEle.on("keydown", function (event) {
            //
            console.log(event.keyCode);
            if (event.keyCode === 17) {
                // 進入批量操做模式
                mode = true;
            }
        });
        // 按鍵擡起來的時候,退出批量操做模式
        $bodyEle.on("keyup", function (event) {
            //
            console.log(event.keyCode);
            if (event.keyCode === 17) {
                // 進入批量操做模式
                mode = false;
            }
        });

        $("select").on("change", function () {
            // 取到當前select的值
            var value = $(this).val();
            // console.log(value);
            var $thisCheckbox = $(this).parent().siblings().first().find(":checkbox");
            // 判斷checkbox有沒有被選中
            if ($thisCheckbox.prop("checked") && mode) {
                // 真正進入批量操做模式
                var $checkedEles = $("input[type='checkbox']:checked");
                for (var i = 0; i < $checkedEles.length; i++) {
                    // 找到同一行的select
                    $($checkedEles[i]).parent().siblings().last().find("select").val(value);
                }
            }
        })
    });
</script>
</body>
</html>
鍵盤事件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>08動畫效果</title>
</head>
<body>
<img src="https://www.python.org/static/img/python-logo.png" alt="">
<img src="test.png" alt="">
<script src="jquery-3.3.1.min.js"></script>

<script>
    $("img").hide(5000);
    $("img").toggle(5000);
</script>
</body>
</html>
動畫效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
      <div id="id2" style="display:none; width: 80px;height: 80px;background-color: orangered "></div>
      <div id="id3" style="display:none; width: 80px;height: 80px;background-color: darkgreen "></div>

    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#in").click(function(){
               $("#id1").fadeIn(3000);
               $("#id2").fadeIn(3000);
               $("#id3").fadeIn(3000);

            });
            $("#out").click(function(){
               $("#id1").fadeOut(3000);
               $("#id2").fadeOut(3000);
               $("#id3").fadeOut(3000);

            });
            $("#toggle").click(function(){
               $("#id1").fadeToggle(3000);
               $("#id2").fadeToggle(3000);
               $("#id3").fadeToggle(3000);

            });
            $("#fadeto").click(function(){
               $("#id1").fadeTo(3000,0.4);
               $("#id2").fadeTo(3000,0.5);
               $("#id3").fadeTo(3000,0);
            });
        });
    </script>
</body>
</html>
淡入淡出

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;

        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>

    <div id="flipshow">出現</div>
    <div id="fliphide">隱藏</div>
    <div id="toggle">toggle</div>
    <div id="content">helloworld</div>

    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(document).ready(function(){
              $("#flipshow").click(function(){
                 $("#content").slideDown(1000);
              });
              $("#fliphide").click(function(){
                 $("#content").slideUp(1000);
              });
              $("#toggle").click(function(){
                 $("#content").slideToggle(1000);
              })
          });
    </script>

</body>
</html>
滑動
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <title>購物商城</title>

    <style>
            *{
                margin: 0;
                padding: 0;
            }
            .outer{
                position:relative;
                width:350px;
                height:350px;
                border:1px solid black;
            }
            .outer .small-box{
                position: relative;
                z-index: 1;
            }
            .outer .small-box .mark{
                position: absolute;
                display: block;
                width: 350px;
                height: 350px;
                background-color: #fff;
                filter: alpha(opacity=0);
                opacity: 0;
                z-index: 10;
            }
            .outer .small-box .float-box{
                display: none;
                width: 175px;
                height: 175px;
                position: absolute;
                background: #DAEEFC;
                filter: alpha(opacity=40);
                opacity: 0.4;
            }
            .outer .big-box{
                position: absolute;
                top: 0;
                left: 351px;
                width: 350px;
                height: 350px;
                overflow: hidden;
                border: 1px solid transparent;
                z-index: 1;
            }
            .outer .big-box img{
                position: absolute;
                z-index: 5
            }
    </style>
</head>
<body>

    <div  class="outer">
        <div  class="small-box">
            <div  class="mark"></div>
            <div  class="float-box" ></div>
            <img width="350" height="350" src="1.jpg">
        </div>
        <div class="big-box">
            <img width="900px" height="900px" src="1.jpg" >
        </div>
    </div>


<script src="jquery-3.3.1.min.js"></script>

<script>
   $(function(){
        $(".mark").mouseover(function () {
            $(".float-box").css("display","block");
            $(".big-box").css("display","block");
        });

        $(".mark").mouseout(function () {
            $(".float-box").css("display","none");
            $(".big-box").css("display","none");
        });



        $(".mark").mousemove(function (e) {

            var _event = e || window.event;  //兼容多個瀏覽器的event參數模式

            var float_box_width  = $(".float-box")[0].offsetWidth;
            var float_box_height = $(".float-box")[0].offsetHeight;//175,175


            var float_box_width_half  =  float_box_width / 2;
            var float_box_height_half =  float_box_height/ 2;//87.5,87.5


            var small_box_width  =  $(".outer")[0].offsetWidth;
            var small_box_height =  $(".outer")[0].offsetHeight;//360,360


            var mouse_left = _event.clientX   - float_box_width_half;
            var mouse_top = _event.clientY  - float_box_height_half;


            if (mouse_left < 0) {
                mouse_left = 0;
            } else if (mouse_left > small_box_width - float_box_width) {
                mouse_left = small_box_width - float_box_width;
            }
            if (mouse_top < 0) {
                mouse_top = 0;
            } else if (mouse_top > small_box_height - float_box_height) {
                mouse_top = small_box_height - float_box_height;
            }

            $(".float-box").css("left",mouse_left + "px");
            $(".float-box").css("top",mouse_top + "px");


            var percentX = ($(".big-box img")[0].offsetWidth - $(".big-box")[0].offsetWidth) / (small_box_width - float_box_width);
            var percentY = ($(".big-box img")[0].offsetHeight - $(".big-box")[0].offsetHeight) / (small_box_height - float_box_height);
            console.log($(".big-box img")[0].offsetWidth,$(".big-box")[0].offsetWidth,small_box_width,float_box_width)
            console.log(percentX,percentY)
            $(".big-box img").css("left",-percentX * mouse_left + "px");
            $(".big-box img").css("top",-percentY * mouse_top + "px")

        })
   })

</script>
</body>
</html>
商品放大
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .shade{
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,.6) ;
            z-index: 20;
        }
        .modal{
            position: fixed;
            left: 50%;
            top: 50%;
            height: 300px;
            width: 400px;
            margin-top: -150px;
            margin-left: -200px;
            z-index: 30;
            border: 1px solid #ddd;
            background-color: white;
        }
        .hide{
            display: none;
        }
        .modal form {
            position: fixed;
            left: 50%;
            top: 50%;
            height: 200px;
            width: 229px;
            border: 1px;
            margin-left: -115px;
            margin-top: -100px;
        }
        .modal form p {
            float: right;
            margin-top: 12px;
        }
        .modal form span {
            float: right;
            display: inline-block;
            height: 18px;
            width: 170px;
            background-color: #FFEBEB;
            text-align: center;
            border: 1px solid #ffbdbe;
            color: #e4393c;
            font-size: 14px;
            visibility: hidden;
        }
        .modal form [type="button"] {
            position: absolute;
            bottom: -30px;
            left: 115px;
        }
        .modal form [value="提交"]{
            left: 50px;
        }
    </style>
</head>
<body>
    <div style="width: 300px; margin: 0 auto">
        <input type="button" value="添加主機" onclick="return Add();" />
        <table style="border: 2px solid #F5F5F5; width: 300px;">
            <thead>
                <tr>
                    <th >主機名</th>
                    <th >IP</th>
                    <th >端口</th>
                    <th>操做</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td target="host">c1.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td onclick="Edit(this);">Edit</td>
                </tr>
               <tr>
                    <td target="host">c2.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td onclick="Edit(this);">Edit</td>
                </tr>
                <tr>
                    <td target="host">c3.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td onclick="Edit(this);">Edit</td>
                </tr>
                <tr>
                    <td target="host">.com</td>
                    <td target="ip">1.1.1.1</td>
                    <td target="port">8888</td>
                    <td onclick="Edit(this);">Edit</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="shade hide"></div>
    <div  class="modal hide">
        <form action="" method="get">
            <p>主機名:<input type="text" id="host" name="host"><br><span></span></p>
            <p>IP地址:<input type="text" id='ip' name="ip"><br><span></span></p>
            <p>端口號:<input type="text" id='port' name="port"><br><span></span><br></p>
            <input type="button" value="提交" onclick="return SubmitForm();">
            <input type="button" value="取消" onclick="HideModal();">
        </form>
    </div>

    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
           $("tr:even").css("background-color","#f5f5f5");
        });
        function Edit(ths) {
            $(".shade,.modal").removeClass("hide");
            prevList = $(ths).prevAll();
            prevList.each(function () {
                var text = $(this).text();
                var target = $(this).attr("target");
                $("#"+target).val(text);
            });
        }
        function HideModal() {
            $(".shade,.modal").addClass("hide");
            $(".modal").find("input[type='text']").val("");
            Addd = false;
        }
        function SubmitForm() {
            var flag = Detection();

            try {
                    if (Addd && flag){
                    $("tbody").append($("tr").last().clone());
                    $(".modal").find("input[type='text']").each(function () {
                        var value = $(this).val();
                        var name = $(this).attr("name");
                        ($("tr").last().children()).each(function () {
                            if ($(this).attr("target") == name){
                                $(this).text(value);
                                return
                            }
                                }
                        )});
                    Addd = false;
                    HideModal();
                    return false;
                }
            }catch (e){}


            if (flag){
                $(".modal").find("input[type='text']").each(function () {
                    var value = $(this).val();
                    var name = $(this).attr("name");
                    $(prevList).each(function () {
                        if ($(this).attr("target") == name){
                            $(this).text(value);
                            return
                        }
                            }
                    )});
                    $(".modal,.shade").addClass("hide");
                    HideModal();
                }
            return flag;
            }


        function Detection() {
            var flag = true;
            $(".modal").find("input[type='text']").each(function () {
                var value = $(this).val();
                if (value.length == 0){
                    $(this).next().next().css("visibility","visible").text("親,不能爲空");
                    flag = false;
                    return false;
                }else {
                    $(this).next().next().css("visibility","hidden").text("");
                }

                if ($(this).attr('name') == "host"){
                    var r = /(\.com)$/;
                    if (r.test(value) == false){
                        $(this).next().next().css("visibility","visible").text("主機名必須以.com結尾");
                        flag = false;
                        return false;
                }
                }else if ($(this).attr('name') == "ip"){
                    var r2 = /^(([0-2]?[0-9][0-9]?)\.){3}([0-2]?[0-9][0-9]?)$/;
                    if (r2.test(value) == false){
                        $(this).next().next().css("visibility","visible").text("ip 地址格式有誤");
                        flag = false;
                        return false;
                    }
                }else if ($(this).attr('name') == "port"){
                    var r3 = /^([0-9]{1,5})$/;
                    if ((r3.test(value) == false) || (value > 65535)){
                        $(this).next().next().css("visibility","visible").text("端口必須爲0-65535");
                        flag = false;
                        return false;
                    }
                }else {
                    $(this).next().next().css("visibility","hidden").text("");
                }
        });
        return flag;
        }

        function Add() {
            Addd = true;
            $(".shade,.modal").removeClass("hide");
        }
    </script>
</body>
</html>
模態框加增長修改數據
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            list-style: none;
        }
        .out{
            width: 730px;
            height: 454px;
            margin: 50px auto;
            position: relative;
        }
        .out .img li{
            position: absolute;
            left: 0;
            top: 0;
        }
        .out .num{
            position: absolute;
            left:0;
            bottom: 20px;
            text-align: center;
            font-size: 0;
            width: 100%;
        }
        .out .btn{
            position: absolute;
            top:50%;
            margin-top: -30px;
            width: 30px;
            height: 60px;
            background-color: aliceblue;
            color: black;
            text-align: center;
            line-height: 60px;
            font-size: 40px;
            display: none;
        }
        .out .num li{
            width: 20px;
            height: 20px;
            background-color: black;
            color: #fff;
            text-align: center;
            line-height: 20px;
            border-radius: 60%;
            display: inline;
            font-size: 18px;
            margin: 0 10px;
            cursor: pointer;
        }
        .out .num li.active{
            background-color: red;
        }
        .out .left{
            left: 0;
        }
        .out .right{
            right: 0;
        }
        .out:hover .btn{
            display: block;
            color: white;
            font-weight: 900;
            background-color: black;
            opacity: 0.8;
            cursor: pointer;
        }
        .out img {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
     <div class="out">
         <ul class="img">
             <li><a href="#"><img src="images/1.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/2.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/3.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/4.jpg" alt=""></a></li>
             <li><a href="#"><img src="images/5.jpg" alt=""></a></li>
         </ul>

         <ul class="num">
             <!--<li class="active">1</li>-->
             <!--<li>2</li>-->
             <!--<li>3</li>-->
             <!--<li>4</li>-->
             <!--<li>5</li>-->
         </ul>

         <div class="left btn"><</div>
         <div class="right btn">></div>

     </div>

    <script src="jquery-3.3.1.min.js"></script>
    <script>

        $(function(){
            var size=$(".img li").size();
            for (var i= 1;i<=size;i++){
                var li="<li>"+i+"</li>";
                $(".num").append(li);
            }
            $(".num li").eq(0).addClass("active");


            $(".num li").mouseover(function(){
               $(this).addClass("active").siblings().removeClass("active");
               var index=$(this).index();
               i=index;
               $(".img li").eq(index).fadeIn(1000).siblings().fadeOut(1000);
            });


        i=0;
        var t=setInterval(move,1500);

        function move(){
            i++;
            if(i==size){
                i=0;
            }
            $(".num li").eq(i).addClass("active").siblings().removeClass("active");
            $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
        }

        function moveL(){
            i--;
            if(i==-1){
                i=size-1;
            }
            $(".num li").eq(i).addClass("active").siblings().removeClass("active");
            $(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
        }

        $(".out").hover(function(){
            clearInterval(t);
        },function(){
            t=setInterval(move,1500);
        });

        $(".out .right").click(function(){
            move()
        });
        $(".out .left").click(function(){
           moveL()
        })

        });
    </script>

</body>
</html>
輪播圖
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .edit-mode{
            background-color: #b3b3b3;
            padding: 8px;
            text-decoration: none;
            color: white;
        }
        .editing{
            background-color: #f0ad4e;
        }
    </style>
</head>
<body>

    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全選" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反選" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />

        <a id="edit_mode" class="edit-mode" href="javascript:void(0);"  onclick="EditMode(this, '#tb1');">進入編輯模式</a>

    </div>
    <table border="1">
        <thead>
        <tr>
            <th>選擇</th>
            <th>主機名</th>
            <th>端口</th>
            <th>狀態</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在線</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下線</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在線</td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script>
        /*
         監聽是否已經按下control鍵
         */
        window.globalCtrlKeyPress = false;

        window.onkeydown = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = true;
            }
        };
        window.onkeyup = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = false;
            }
        };

        /*
         按下Control,聯動表格中正在編輯的select
         */
        function MultiSelect(ths){
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }
    </script>
    <script type="text/javascript">

$(function(){
    BindSingleCheck('#edit_mode', '#tb1');
});

function BindSingleCheck(mode, tb){

    $(tb).find(':checkbox').bind('click', function(){
        var $tr = $(this).parent().parent();
        if($(mode).hasClass('editing')){
            if($(this).prop('checked')){
                RowIntoEdit($tr);
            }else{
                RowOutEdit($tr);
            }
        }
    });
}

function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
    var sel= document.createElement('select');
    $.each(attrs,function(k,v){
        $(sel).attr(k,v);
    });
    $.each(csses,function(k,v){
        $(sel).css(k,v);
    });
    $.each(option_dict,function(k,v){
        var opt1=document.createElement('option');
        var sel_text = v[item_value];
        var sel_value = v[item_key];

        if(sel_value==current_val){
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
        }else{
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
        }
    });
    return sel;
}

STATUS = [
    {'id': 1, 'value': "在線"},
    {'id': 2, 'value': "下線"}
];

BUSINESS = [
    {'id': 1, 'value': "車上會"},
    {'id': 2, 'value': "二手車"}
];

function RowIntoEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var select_val = $(this).attr('sel-val');
                var global_key = $(this).attr('global-key');
                var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                $(this).html(selelct_tag);
            }else{
                var orgin_value = $(this).text();
                var temp = "<input value='"+ orgin_value+"' />";
                $(this).html(temp);
            }

        }
    });
}

function RowOutEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var new_val = $(this).children(':first').val();
                var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                $(this).attr('sel-val', new_val);
                $(this).text(new_text);
            }else{
                var orgin_value = $(this).children().first().val();
                $(this).text(orgin_value);
            }

        }
    });
}

function CheckAll(mode, tb){
    if($(mode).hasClass('editing')){

        $(tb).children().each(function(){

            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){

            }else{
                check_box.prop('checked',true);

                RowIntoEdit(tr);
            }
        });

    }else{

        $(tb).find(':checkbox').prop('checked', true);
    }
}

function CheckReverse(mode, tb){

    if($(mode).hasClass('editing')){

        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);
            }else{
                check_box.prop('checked',true);
                RowIntoEdit(tr);
            }
        });


    }else{

        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
            }else{
                check_box.prop('checked',true);
            }
        });
    }
}

function CheckCancel(mode, tb){
    if($(mode).hasClass('editing')){
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);

            }else{

            }
        });

    }else{
        $(tb).find(':checkbox').prop('checked', false);
    }
}

function EditMode(ths, tb){
    if($(ths).hasClass('editing')){
        $(ths).removeClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowOutEdit(tr);
            }else{

            }
        });

    }else{

        $(ths).addClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowIntoEdit(tr);
            }else{

            }
        });

    }
}


    </script>

</body>
</html>
編輯加聯動
相關文章
相關標籤/搜索