JSLite 與jQuery有着相似的api,模仿jQuery的語法規範,並非100%的覆蓋【官方文檔】

[JSLite.io]

GitHub issues GitHub forks GitHub stars GitHub license Gitter Built with Grunt

若有疑問歡迎到這些地方交流,歡迎加入JSLite.io組織團伙共同開發! javascript

QQ交流羣:397463673
segmentfault社區 | 官方網站 | 官方文檔-更詳細 | Issuesphp

  1. jQuery 的目標是兼容全部主流瀏覽器,這就意味着它的大量代碼對移動端的瀏覽器是無用或者低效的。css

  2. 而 JSLite 只針對先進瀏覽器(支持HTML5,CSS3)、移動端瀏覽器編寫,使用js新方法實現jQuery API,所以體積更小、效率更高.html

  3. 更重要的是,JSLite 的 API 徹底仿照 jQuery ,因此學習成本也很低。前端

  4. JSLite與jQuery有着絕大部分相似的api,通用庫只有5-10k,手機上每一kb都是錢。java

  5. 讓web開發更迅速,下載執行更快、量級更輕,針對現代高級瀏覽器的JavaScript庫。 推動前端開發標準對於攻城師來講,人人有責。node

瀏覽器兼容

此兼容,是根據我使用的一些js方法函數的支持狀況來判斷的。設備過少,部分是根據developer.mozilla.org的方法函數兼容數據來判斷的,下面的咱們的主要兼容目標jquery

Safari 6+ (Mac)
Chrome 30+ (Windows, Mac, Android, iOS, Linux, Chrome OS)
Firefox 24+ (Windows, Mac, Android, Linux, Firefox OS)
iOS 5+ Safari
Android 2.3+ Browser
Internet Explorer 10+ (Windows, Windows Phone)git

安裝

npm

$ npm install jslite

NPM

傳統方法

  1. 官網下載JSLite,github downloadgithub

  2. 頁面Head標籤內引用 JSLite.js

<script type="text/javascript" src="JSLite.js"></script>

核心

$()

選擇器使用的是瀏覽器自帶的方法的 document.querySelectorAll 接口,支持標準的 CSS 選擇器,沒有使用jQuery做者John Resig開發的DOM選擇器引擎(Dom Selector Engine) Sizzle 。目前 IE8/9及Firefox/Chrome/Safari/Opera 的最新版已經支持 querySelectorAll
$(selector) //⇒ 選擇節點
$("<DOM nodes>") //⇒ 生成節點
$("htmlString") //⇒ 生成
JSLite(function($){ ... }) //⇒ 至關於ready

$("#box") //⇒ 返回節點數組  //⇒ [<div>​…​</div>​]
$("<div></div>") //⇒ 生成div節點
//JSLite(func) 至關於ready
JSLite(function($){
    console.log("在節點加載完成以後執行")
})
//$(func) 至關於ready
$(function($){
    console.log("在節點加載完成以後執行")
})

JSLite()

與$()相同。

noConflict

noConflict() 方法讓渡變量 $ 的 JSLite 控制權,解決倆庫之間的$衝突。
該方法釋放 JSLite 對 $ 變量的控制。
該方法也可用於爲 JSLite 變量規定新的自定義名稱。

實例一
$.noConflict();
JSLite(document).ready(function($) {
// 使用 JSLite $ 的代碼
});
// 使用其餘庫的 $ 的代碼
實例二

將 $ 引用的對象映射回原始的對象:

JSLite.noConflict();
JSLite("div p").hide(); // 使用 JSLite
$("content").style.display = "none";    // 使用其餘庫的 $()
實例三

恢復使用別名 $,而後建立並執行一個函數,在這個函數的做用域中仍然將 $ 做爲 JSLite 的別名來使用。在這個函數中,原來的 $ 對象是無效的。這個函數對於大多數不依賴於其餘庫的插件都十分有效:

JSLite.noConflict();
(function($) { 
  $(function() {
    // 使用 $ 做爲 JSLite 別名的代碼
  });
})(JSLite);

... // 其餘用 $ 做爲別名的庫的代碼
實例四

能夠將 JSLite.noConflict() 與簡寫的 ready 結合,使代碼更緊湊

JSLite.noConflict()(function(){
    // 使用 JSLite 的代碼
    console.log($('div'))
});
實例五

建立一個新的別名用以在接下來的庫中使用 JSLite 對象:

var j = JSLite.noConflict();
j("#box").hide();  // 基於 JSLite 的代碼
$("content").style.display = "none";    // 基於其餘庫的 $() 代碼
實例六

徹底將 JSLite 移到一個新的命名空間:

var dom = {};
dom.jslite = JSLite.noConflict(true);

結果:

dom.jslite("div p").hide();  // 新 JSLite 的代碼
$("content").style.display = "none";    // 另外一個庫 $() 的代碼
JSLite("div > p").hide();   // 另外一個版本 JSLite 的代碼

插件編寫

$.extend

經過源對象擴展目標對象的屬性,擴展 JSLite 元素集來提供新的方法(一般用來製做插件)

$.extend({
    min: function(a, b) { return a < b ? a : b; },
    max: function(a, b) { return a > b ? a : b; }
});
$.min(2,3);    //⇒ 2
$.max(4,5);    //⇒ 5
// 在$上擴展了幾個方法  
//調用方法  $.min(2,3);   //⇒ 2
//調用方法  $.max(4,5);   //⇒ 5

$.fn.extend

擴展 JSLite 元素集來提供新的方法(一般用來製做插件)。

$.fn.extend({   //增長兩個插件方法。
    check: function() {
        return this.each(function() { this.checked = true; });
    },
    uncheck: function() {
        return this.each(function() { this.checked = false; });
    }
});
$("input[type=checkbox]").check();  //選中
$("input[type=radio]").uncheck();   //取消選中

$.error

當元素遇到錯誤(沒有正確載入)時,發生 error 事件。

$.error("2222")
//⇒ 輸出錯誤 Uncaught 2222

字符串處理

$.trim

去掉字符串起始和結尾的空格。

$.trim("  hello, how are you?  ");//⇒ "hello, how are you?"

trim

同上,去掉字符串起始和結尾的空格。

"  hello, how are you?  ".trim()//⇒ "hello, how are you?"

URL

$.getUrlParam

獲取 url 參數的值。

//[URL] = http://blog.pc175.com/?param=2
$.getUrlParam("param") //⇒ 2

$.param

將表單元素數組或者對象序列化。若是shallow設置爲true,嵌套對象不會被序列化,嵌套數組的值不會使用放括號在他們的key上。
$.param(object, [shallow]) ⇒ string
$.param(array) ⇒ string

$.param({
    foo: {one: 1,two: 2 }
})  //⇒ "foo[one]=1&foo[two]=2"

$.param({
    ids:["a1","b2","c3"],
    c:{g:23,e:[567]},
    a:3
},true) //⇒ ids=a1&&ids=b2&&ids=c3&&c=[object Object]&a=3

$.param({
    ids:["a1","b2","c3"],
    c:{g:23,e:[567]},
    a:3
}) //⇒ ids[]=a1&&ids[]=b2&&ids[]=c3&&c[g]=23&&c[e]=567&&a=3

$.param([1,2,3]) //⇒ 0=1&&1=2&&2=3

$.param({
    ids:[1,2,3] 
})  //=> "ids[]=1&ids[]=2&ids[]=3"

數組對象操做

最大(小)值

//順帶小教程
//獲取最大值最小值
var a=[1,2,3,5];
console.log(Math.max.apply(null, a));//最大值
console.log(Math.min.apply(null, a));//最小值

var a=[1,2,3,[5,6],[1,4,8]];
var ta=a.join(",").split(",");//轉化爲一維數組
console.log(Math.max.apply(null,ta));//最大值
console.log(Math.min.apply(null,ta));//最小值

$.intersect

數組交集

$.intersect([1,2,3,'asdkjf'],[2,3,6,'asdkjf'])
//⇒ [2, 3, "asdkjf"]

concat

合併,有可能會重複

[1,2].concat([1,5,6]) //⇒ [1, 2, 1, 5, 6]
$('#box').concat($('[type=submit]')[0]) //與下面同樣  合併到一塊兒了
$('#box').concat($('[type=submit]'))

$.unique

刪除數組中重複元素。

$.unique([1,2,12,3,2,1,2,1,1,1,1]) //⇒ [1, 2, 12, 3]
var arr = $('#box').concat($('#box')) //兩個如出一轍的數組
$.unique(arr) //去重

$.sibling

根據類型獲取節點對象屬性的集合 (node,type)

$.sibling($("input"),"type")    //⇒ ["text", "button", "checkbox"]   
$.sibling($("input"),"tagName") //⇒ ["INPUT"]

$.inArray

搜索數組中指定值並返回它的索引(若是沒有找到則返回-1)。

var arr = [ 4, "Pete", 8, "John" ];
$.inArray("John", arr);     //⇒ 3
$.inArray(4, arr);          //⇒ 0
$.inArray("David", arr);    //⇒ -1
$.inArray("Pete", arr, 2);  //⇒ -1

$.map

經過遍歷集合中的節點對象,經過函數返回一個新的數組,nullundefined 將被過濾掉。

$.map({"w":1,"c":2,"j":3},function(idx,item){
     return item
}); 
//⇒ ["w", "c", "j"]

$.each

通用例遍方法,可用於例遍對象和數組

$.each(['a', 'b', 'c'], function(index, item){
    console.log('item %d is: %s', index, item)
})

$.grep

使用過濾函數過濾數組元素。

$.grep( [0,1,2], function(n,i){
  return n != 0;
});

$.parseJSON

JSON.parse 方法相同,接受一個標準格式的 JSON 字符串,並返回解析後的 JavaScript 對象。


測試操做

$.isDocument

判斷對象是否爲【document】。

$.isDocument(document) //⇒ true

$.isWindow

肯定參數是否爲一個窗口(window對象),若是是則返回true。這在處理iframe時很是有用,由於每一個iframe都有它們本身的window對象,使用常規方法obj==window校驗這些objects的時候會失敗。

$.isFunction

判斷對象是否爲函數【function】。

$.isFunction(function(){}) //⇒ true

$.isObject

判斷是否爲 Object

$.isObject({})  //⇒ true

$.isPlainObject

$.isPlainObject(object) ⇒ boolean
若是經過 "{}" 或者 "new Object" 建立的則返回true。判斷對象是不是純粹的對象。

$.isPlainObject({})         // => true
$.isPlainObject(new Object) // => true
$.isPlainObject(new Date)   // => false
$.isPlainObject(window)     // => false

$.isArray

判斷是否爲【數組】。

$.isArray([1,2,3])  //⇒ true

$.isJson

判斷是否爲【數組】。

$.isJson({})  //⇒ true

$.contains

$.contains(parent, node) ⇒ boolean
parent是否包含node節點對象。

$.isContainsNode($("#box")[0],$(".boxss")[0]) //⇒ parent是否包含node節點對象

$.likeArray

判斷對象是否爲數組或者是字符。

$.likeArray([1,2,3])     //⇒ true
$.likeArray("222")  //⇒ true

$.type

獲取JavaScript 對象的類型。可能的類型有: null undefined boolean number string function array date regexp object error

$.type(true)  //⇒ Boolean
$.type("div") //⇒ String

$.matches

若是當前節點能被指定的css選擇器查找到,則返回true,不然返回false
$.matches(element,selector) ⇒ boolean

$.matches($("#box")[0], "#box")//⇒ true

is

判斷當前匹配的元素集合中的元素,是否爲一個選擇器,DOM元素
is(selector) ⇒ boolean
is(element) ⇒ boolean

$('#box').is('div');  //⇒ true  
$('#box').is('#box');  //⇒ true  
$('#box').is('#boxsss');  //⇒ flase  
$('div').is($('#box')[0]) //⇒ true  節點是否在 $('#box')[0] 是否再集合中

對象訪問

each

遍歷一個 JSLite 集合對象,爲每個匹配元素執行一個函數。this關鍵字指向當前item(做爲函數的第二個參數傳遞)。若是函數返回 false,遍歷結束。

$("img").each(function(i){
    this.src = "test" + i + ".jpg";
});
//⇒ 找到全部的img對象給設置src  
//⇒ 返回 [ <img src="test0.jpg" />, <img src="test1.jpg" /> ]

map

遍歷節點對象集合中的全部節點對象返回一個新的集合對象

$(".box").map(function(index,item){
    return $(this).text()
})
//⇒ 返回 ["12boxOne", "6", "11", "22123456", "7123123"]

forEach

相似 each,forEach遍歷不會中止。

//遍歷數組
[1,5,2,3].forEach(function(item,index,array){
    console.log(item,index,array)
})
//遍歷節點
$("img").forEach(function(item,index,array){
    console.log(item,index,array)
})

eq

指定匹配元素的集合爲的索引的哪個元素。一個整數,指示元素的位置,以 0 爲基數。
eq(index) ⇒ collection
eq(-index) ⇒ collection

$("div").eq(0)//⇒ 返回數組第一個節點數組 [div#box.boxOne.box2.box3, init: function…]
$("div").eq(-1)//⇒ 倒數第一個節點數組
$("div").eq(-2)//⇒ 倒數第二個節點數組

get

當前對象集合中獲取全部節點對象或單個節點對象。

$("div").get(0)//⇒ 返回節點 <div id="box" class="boxOne box2 box3" ></div>

index

獲取一個元素的位置。當elemen參數沒有給出時,返回當前元素在兄弟節點中的位置。
.index() //對象中第一個元素相對於它同輩元素的位置
.index(selector)
.index(element)

$("#box").index()//⇒ 4
$("div").index("#box")//⇒ 2
$("div").index($("#box"))//⇒ 2
$("div").index($("#box")[0])//⇒ 2

indexOf

在當前獲取的節點數組中獲取一個元素在這個數組的位置。

$("div").indexOf($("#box")[0])
//⇒ 2

length

對象中元素的個數。

$("img").length;
//⇒ 2

HTML代碼/文本/值

text

取得全部匹配節點對象的文本內容。

$("#box").text()
//⇒ string 返回文本

html

獲取或設置節點對象內容。

$("#box").html()
//⇒ string 返回包括HTML的文本

val

獲取設置input的 value 。

$('input').val() //⇒ string 
$('input').val('test') //⇒ self 

$('#input').val(function(index,oldvalue){
    console.log(index,oldvalue)
    return '111' + oldvalue
}) //⇒ self

節點屬性

pluck

獲取對象集合中每個元素的屬性值。

$("#box").pluck("nodeName") //⇒ ["DIV"]
$("#box").pluck("nextElementSibling") //⇒ <div class="boxs">1234567890</div>
$("#box").pluck('children') //⇒ [HTMLCollection[4]]

attr

讀取或設置dom的屬性。

$(".button").attr({"class":"","style":"background:red"}) //⇒ self 設置紅色清空class
$(".button").attr("class","name")  //⇒ self 設置class替換以前的
$(".button").attr("class")  //⇒ string 獲取class屬性值

removeAttr

移動當前對象集合中全部元素的指定屬性。

$("#box").removeAttr("class") //⇒ self 移除class

CSS 類

css

獲取或設置節點對象的style樣式內容。

$("#box").css('color','yellow')     //⇒ self 返回Array 節點內容
$("#box").css({'color':'yellow'})   //⇒ self 返回Array 節點內容

hasClass

集合中是否有節點對象含有指定的class。

$("#box").hasClass('box2') //⇒ true

addClass

爲每一個匹配的節點對象添加指定的class類名。

$("#box").addClass('box23 go') //⇒ self 原有對象class上添加 box23和 go

$("#box").addClass(function(){
    return 'box23 wcj'
}) //⇒ self 原有對象class上添加 box23 和wcj

removeClass

清除節點對象中全部節點對象的指定class類名,不填寫清空。

$("#box").removeClass('box23') //⇒ self 刪除原有對象class中box23
$("div").removeClass() //⇒ self  全部匹配的對象class屬性被刪除

toggleClass

在匹配的節點對象集合中的每一個節點對象上添加或刪除一個或多個樣式類。

$("#box").toggleClass('box1 box2') //⇒ self 原有對象class上添加 "box1 box2"或者刪除"box1 box2"

效果

toggle

顯示或隱藏匹配節點對象。

$("#box").toggle() //⇒ self 原有對象若是隱藏就顯示,若是顯示就隱藏。

show

顯示匹配節點對象。

$("#box").show() //⇒ self 顯示匹配節點對象

hide

隱藏匹配節點對象。

$("#box").hide() //⇒ self 隱藏匹配的對象

尺寸位置

offset

得到當前元素相對於document的位置。返回一個對象含有:left|top|width|height

$("#box").offset()  //⇒Object {left: 8, top: 8, width: 1260, height: 0}
$("#box").offset().left  //⇒  8

width

width() ⇒ number
width(value) ⇒ self
width(function(index, oldWidth){ ... }) ⇒ self
獲取對象象集合中第一個元素的寬,或設置對象集合全部元素的寬。

$('#box').width()   // => 342
$(window).width()   // => 456 (可視區域寬度)
$(document).width() // => dsf

height

height() ⇒ number
height(value) ⇒ self
height(function(index, oldWidth){ ... }) ⇒ self
獲取對象象集合中第一個元素的高,或設置對象集合全部元素的高。

$('#box').height()   // => 342
$(window).height()   // => 456 (可視區域高度)
$(document).height() // => dsf

過濾

filter

篩選出與指定表達式匹配的元素集合。filter(selector)

$("div").filter("#box") //⇒ self 在全部的div對象中選擇器爲 #box 的過濾出來。

not

not(selector) ⇒ collection
not(collection) ⇒ collection
not(function(index){ ... }) ⇒ collection
篩選出與 指定表達式匹配的元素集合。它的做用恰好與 filter 相反,返回。

$("#select option").not(function(idx){
    console.log(this.selected)
    return this.selected
})
//⇒ [<option value="3">哈哈3</option>]
$('input').not('#input') //⇒ 返回除去 匹配到的#input

$('input').not(function(){
    console.log(this.type)
    return this.type=='text'
})

刪除節點

empty

全部匹配節點對象集合中移除全部的dom子節點,不包括本身,清空內容。

$("#box").empty()
//⇒ self <div id="box" class="boxOne box2 box3" ></div>

remove

刪除全部匹配節點對象【本身】及全部【本身】裏面的內容。

$("#box").remove()
//⇒ self <div id="box" class="boxOne box2 box3" ></div>

detach !

被遺棄的方法(不建議使用),做用跟remove同樣,全部綁定的事件、附加的數據等都會保留下來。

$("#box").click(function(){
    console.log("wcj")
})
var a = $('#box').detach();//刪除的對象賦給a
$('body').append(a)//將a添加到 body 中仍是能夠點擊

查找節點

find

後代節點的集合(能夠帶上濾選擇器)。

$("#box").find()        //⇒後代節點的集合
$("#box").find(".box")  //⇒後代節點的集合,返回匹配'.box' 的集合

children

得到每一個匹配元素集合元素的直接子元素(能夠帶上濾選擇器)。

$("#box").children()
//下面這種方法也能夠的 CSS3 節點選擇器 -_+
$("#box *")

contents

contents() ⇒ collection
得到每一個匹配元素集合元素的子元素,包括文字和註釋節點。

$("#box").contents()

parent

對象集合中每一個元素的直接父元素。

$("#box").parent()

parents

獲取對象集合每一個元素全部的祖先元素(不包含根元素)。
parents([selector]) ⇒ collection

$("#box").parents()

$("#boxWhy").parents(".boxss")

closest

從元素自己開始,逐級向上級元素匹配,並返回最早匹配selector的祖先元素。若是context節點參數存在。那麼直考慮該節點的後代。這個方法與 parents(selector)有點相像,但他只返回最早匹配的祖先元素。

$("#box").closest('div')

$(document).bind("click", function(e) {
    console.log(e.target)//當前點擊的對象
    $(e.target).closest("li").css('background','red');
});

$("#boxWhy").closest('.boxss',$('#box')[0])//#boxWhy節點的父節點爲:"$('#box')[0]"的子節點".boxss"

prev

獲取對象集合每一個元素的全部上一個對象(能夠帶上濾選擇器)。

$("#box").prev("div")

next

獲取對象集合每一個元素的全部下一個對象(能夠帶上濾選擇器)。

$("#box").next("div")

prevAll

獲取對此對象【上】全部兄弟對象(能夠帶上濾選擇器)。

$("#box").prevAll("div")

nextAll

獲取對此對象【下】全部兄弟對象(能夠帶上濾選擇器)。

$("#box").nextAll("div")

siblings

獲取對此對象【其它】全部兄弟對象(能夠帶上濾選擇器)。

$("#box").siblings()

add

添加元素到匹配的JSLite對象集合

$("#box").siblings()

插入節點方法

prepend

插入到標籤開始標記以後(裏面的第一個)。
prepend(content) ⇒ self
prepend(Function) ⇒ self

$("#box").prepend("dd") //⇒ self
$("#box").prepend(function(){
    return "asdfasdf"
}) //⇒ self

prependTo

將生成的內容插入到匹配的節點標籤開始標記以後。這有點像prepend,可是是相反的方式。
prependTo(selector) ⇒ self

$('<div>test</div>').prependTo('#box')

append

插入到標籤結束標記前(裏面的結尾)。
append(content) ⇒ self
append(Function) ⇒ self

$("#box").append("dd") //⇒ self

$("#box").append(function(){
    return "asdfasdf"
}) //⇒ self

appendTo

appendTo(selector) ⇒ self
將生成的內容插入到匹配的元素標籤結束標記前(裏面的最後)。這個有點像append,可是插入的目標與其相反。

$('<div>test</div>').appendTo('#box')

after

插入到標籤結束標記後。(兄弟節點的下面)
after(content) ⇒ self
after(Function) ⇒ self

$("#box").after("dd") //⇒ self
$("#box").after(function(){
    return "asdfasdf"
}) //⇒ self

insertAfter

插入的對象集合中的元素到指定的每一個元素後面的dom中。這個有點像 after,可是使用方式相反。
insertAfter(selector) ⇒ self

$('<p>test</p>').insertAfter('#box') //⇒ self
$('#input').insertAfter('#box')        //⇒ self  $('#input')

before

插入到標籤開始前。
after(content) ⇒ self
after(Function) ⇒ self

$("#box").before($('input')) //⇒ self
$("#box").before(function(){
    return "asdfasdf"
}) //⇒ self

insertBefore

insertBefore(selector) ⇒ self
將生成的內容插入 selector 匹配的節點標籤開始前。這個有點像 before,可是使用方式相反。

$('<p>test</p>').insertBefore('#box')

clone

clone() ⇒ collection
經過深度克隆來複制集合中的全部元素。(經過原生 cloneNode 方法深度克隆來複制集合中的全部元素。此方法不會有數據和事件處理程序複製到新的元素。這點和jquery中利用一個參數來肯定是否複製數據和事件處理不相同。)

$('body').append($("#box").clone())

事件處理

blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error 對象上直接添加事件。

$("#box").click(function(){
    console.log("綁定點擊事件")
});

ready

ready(function($){ ... }) ⇒ self
添加一個事件偵聽器,當頁面 dom 加載完畢 DOMContentLoaded 事件觸發時觸發。加載完畢執行,建議使用 $(func) 來代替這種用法。

$(document).ready(function(){
    alert("當頁面dom加載完畢執行");
    console.log($("#box"));
})

$(func)

加載完畢執行。與 ready 方法相同

//或者使用下面方法代替ready
$(function(){
    console.log("當頁面dom加載完畢執行");
})

bind

爲每一個匹配元素的特定事件綁定事件處理函數。能夠綁定這些事件 blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error paste drop dragover

$("#box").bind("click", function(){
    console.log("綁定點擊事件")
});

unbind

解除綁定事件,從每個匹配的節點對象中刪除綁定的事件。

var f1=function(){alert('41');}
$("#box").bind("click",f1)   //⇒ 綁定事件
$("#box").unbind("click",f1) //⇒ 解除綁定事件

$("#box").bind("click",function(){alert('41');})   //⇒ 綁定事件
$("#box").unbind("click",function(){alert('41');}) //⇒ 解除綁定事件

on

爲每一個匹配元素的特定事件綁定事件處理函數。能夠綁定這些事件 blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error paste drop dragover

$("#box").on("click", function(){
    console.log("綁定點擊事件")
});

$("#box").on('click mouseover',function(evn){
    console.log('2'+evn)
}) //⇒ self  綁定兩個事件

$("#box").on("click",{val:1},function(){//傳參數
    console.log("dddd","event.data.val = " + event.data.val)
})

$( "#box" ).on({ //綁定多個事件
    click: function() {
        $( this ).css("background","red");
    }, 
    mouseover: function() {
        $( this ).css("background","yellow")
    },
    mousedown: function() {
        $( this ).css("background","green")
    }
});

off

解除綁定事件,從每個匹配的節點對象中刪除綁定的事件。

var f1=function(){alert('41');}
$("#box").on("click",f1)   //⇒ 綁定事件
$("#box").off("click",f1) //⇒ 解除綁定事件

$("#box").on("click",function(){alert('41');})   //⇒ 綁定事件
$("#box").off("click",function(){alert('41');}) //⇒ 解除綁定事件

trigger

trigger(event, [args]) ⇒ self
匹配到的節點集合的元素上觸發指定的事件。若是給定args參數,它會做爲參數傳遞給事件函數。

$("#box").on('abc:click',function(evn,a,c){
    console.log('2'+a+c)
}) //⇒ self  綁定一個事件
$("#box").trigger('abc:click',['wwww']) //⇒ self 觸發並傳一個參數進去

Ajax

執行Ajax請求。
type:請求方法 ("GET", "POST")
data:(默認:none)發送到服務器的數據;若是是get請求,它會自動被做爲參數拼接到url上。非String對象
processData (默認: true): 對於非Get請求。是否自動將 data 轉換爲字符串。
dataType:(json, jsonp, xml, html, or text)
contentType:一個額外的"{鍵:值}"對映射到請求一塊兒發送
headers:(默認:{}): 一個額外的"{鍵:值}"對映射到請求一塊兒發送
url:發送請求的地址
async:此參數不傳默認爲true(同步請求),false異步請求
success(cdata):請求成功以後調用。傳入返回後的數據,以及包含成功代碼的字符串。
error(status, statusText):請求出錯時調用。 (超時,解析錯誤,或者狀態碼不在HTTP 2xx)。

$.get

$.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType]) ⇒ XMLHttpRequest

$.get('http://127.0.0.1/api.php?wcj=123', function(cdata) {
    console.log('ok', cdata)
},'json')

$.get('http://127.0.0.1/api.php?wcj=123',{"JSLite":4}, function(cdata) {
    console.log('ok', cdata)
})

$.ajax(GET)

JSLite獨有....
$.ajax('GET', 'http://127.0.0.1/api.php', {"wcj":"123","ok":'11'},function(cdata) {
    console.log('ok', cdata)
})
通用調用方法
$.ajax({
    type:'GET',
    dataType:'json',
    data:{'nike':'a'},
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    }
})

$.post

$.post(url, [data], function(data, status, xhr){ ... }, [dataType])

$.post('http://127.0.0.1/api.php', {'nike':0},
function(cdata) {
    console.log('ok', cdata)
})

$.ajax(POST)

JSLite獨有....
var data = { 'key': 'key', 'from': 'from'}
$.ajax('POST', 'http://127.0.0.1/api.php', data,function(data) {
    console.log('ok', data)
},'json')
通用調用方法
$.ajax({
    type:'POST',
    dataType:'json',
    data:{"nike":"123","kacper":{"go":34,"to":100}},
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    }
})
$.ajax({
    type:'POST',
    dataType:'json',
    data:JSON.stringify('{"nike":"123","kacper":{"go":34,"to":100}}'),
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    }
})

$.ajax({
    type:'POST',
    dataType:'json',
    data:JSON.stringify({'nike':'a'}),
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    }
})

$.ajax({
    type:'POST',
    data:{'nike':'a'},
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    }
})

$.ajax({
    type:'POST',
    dataType:'json',
    data:{'nike':'a'},
    url:'http://127.0.0.1/api.php',
    success:function(data){
       console.log('success:',data)
    },
    error:function(d){
       console.log('error:',d)
    },
    headers: {
        "Access-Control-Allow-Origin":"http://pc175.com",
        "Access-Control-Allow-Headers":"X-Requested-With"
    },
    contentType: 'application/json'
})

Form

表單提交的一些方法

submit

submit() 方法把表單數據提交到 Web 服務器。這個是原生態提供的方法,尚未封裝更改 *。

$('form')[0].submit() //此處直接原生態提交表單,往後封裝,直接在JSLite對象上就能夠提交。

serializeArray

將用做提交的表單元素的值組合成擁有name和value的鍵值對組成的數組。不能使用的表單元素,buttons,未選中的radio buttons/checkboxs 將會被跳過。結果不包含file inputs的數據。

$('form').serializeArray();
//=> [{"name":"golang","value":"456"},{"name":"name","value":""},{"name":"password","value":""},{"name":"sel","value":[]},{"name":"kaikai","value":""},{"name":"w","value":""},{"name":"w","value":""}]

serialize

將表單元素數組或者對象序列化。

$('form').serialize();
//=> golang=456&name=&password=&sel=&kaikai=&w=asd&w2=asdf

圖片描述

相關文章
相關標籤/搜索