jQuery-Utils
$.contains(document.getElementsByTagName('html')[0],document.getElementsByTagName('body')[0]); //true
$.contains(document.getElementsByTagName('html')[0],document.getElementsByTagName('body')); //false
<div id="container">
<ul id="bottom-nav">
<li id="nav-fist"></li>
<li id="nav-sec"></li>
</ul>
</div>
var $container = $('#container'),
$bottomNav = $('#bottom-nav'),
$itemFirst = $('#nav-fist'),
$itemSec = $('#nav-sec');
$.contains($container, $bottomNav); //false
$.contains($container[0], $bottomNav[0]); //true
$.contains($container[0], $itemFirst); //false
$.contains($container[0], $itemFirst[0]); //true
遍历方法jQuery.each()和jQuery.map()
jQuery.each()
var arr1 = [52, 97];
var arr2 = $.each(arr1, function(index, value) {
console.log(index + ": " + value);
});
// 0: 52
// 1: 97
arr1===arr2; //true
var obj1 = {
p1: "hello",
p2: "world"
};
var obj2 = $.each(obj1, function(key, value) {
console.log(key + ": " + value);
});
// p1: hello
// p2: world
obj1===obj2; // true
var divArray = $('div').get();
$.each(divArray, function(index, dom) {
console.log(index, dom.className);
});
// 0 "container"
// 1 "doc-cata"
// 2 "nicescroll-rails nicescroll-rails-vr"
// 3 "nicescroll-cursors"
// 4 "nicescroll-rails nicescroll-rails-hr"
// 5 "nicescroll-cursors"
jQuery.map()
//DEMO1
var arr1 = ["a", "b", "c", "d", "e"];
var arr2 = $.map(arr1, function (n, i){
return (n.toUpperCase() + i);
});
arr2; //["A0", "B1", "C2", "D3", "E4"]
//DEMO2
var obj1 = {
p1: "hello",
p2: "world"
};
var arr3 = $.map(obj1, function(val, key) {
return (val.toUpperCase() + "_" + key);
});
arr3; //["HELLO_p1", "WORLD_p2"]
//DEMO3 由于在传入函数中未使用return返回出数据,所以map方法的返回值是一个空数组
var arr4 = $.map(obj1, function(val) {
console.log(val.toUpperCase());
});
// HELLO
// WORLD
arr4; // []
//DEMO4
var arr5 = $.map(arr1, function(n, i) {
if (i % 2 == 0 && (n == 'a' || n == 'c')) {
return n.toUpperCase();
} else {
return n + n;
}
});
arr5; //["A", "bb", "C", "dd", "ee"]
jQuery.extend()
var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97 }; var object2 = { banana: { price: 200 }, durian: 100 };
// Merge object2 into object1 var obj3 = $.extend( object1, object2 ); obj3 === object1;//true JSON.stringify( object1 ); //"{“apple”:0,“banana”:{“price”:200},“cherry”:97,“durian”:100}"
<p>我们可以看出,方法的返回值和target是严格相等的,是对target进行修改后直接返回的。有时候需要合并,但是不希望修改原来的对象,我们可以将target传递一个空对象进去。如下所示:</p>
```javascript:n
var tabDefaultSettings={
allowRefresh:true,
allowMax:true,
allowClose:true
};
var options={
id:'home',
name:'首页',
allowClose:false
};
var settings = $.extend( {}, tabDefaultSettings, options );
JSON.stringify(settings);
//"{"allowRefresh":true,"allowMax":true,"allowClose":false,"id":"home","name":"首页"}"
tabDefaultSettings;
//Object {allowRefresh: true, allowMax: true, allowClose: true}
//with deep
var obj1 = { name: "John", location: { city: "Boston", county: "USA" }, p1: ['a', 'b'] },
obj2 = { last: "Resig", location: { state: "MA", county: "China" } };
var resWithDeep = $.extend(true, {}, obj1, obj2);
JSON.stringify(resWithDeep, null, 4);
//console show:
{
"name": "John",
"location": {
"city": "Boston",
"county": "China",
"state": "MA"
},
"p1": [
"a",
"b"
],
"last": "Resig"
}
obj1.p1[0] = 'c';
resWithDeep.p1;//["a", "b"]
// without deep
var obj1 = { name: "John", location: { city: "Boston", county: "USA" }, p1: ['a', 'b'] },
obj2 = { last: "Resig", location: { state: "MA", county: "China" } };
var resNotDeep = $.extend({}, obj1, obj2);
JSON.stringify(resNotDeep, null, 4);
//console show:
{
"name": "John",
"location": {
"state": "MA",
"county": "China"
},
"p1": [
"a",
"b"
],
"last": "Resig"
}
obj1.p1[0] = 'c';
resNotDeep.p1; //["c", "b"]
var src = {
info: 'a library of JavaScript',
introduce: function() {
console.log('welcome to use jQuery, I am', this.info, '!');
}
}
$.extend(src);
$.info; //"a library of JavaScript"
$.introduce(); //welcome to use jQuery, I am a library of JavaScript !
jQuery.fn.extend()
姓名:
<input id="name" name="name" type="text" >
<br>
<input name="opt" type="checkbox" value="A">A
<input name="opt" type="checkbox" value="B">B
<input name="opt" type="checkbox" value="C">C
<input name="opt" type="checkbox" value="D">D
<br>
<input id="btn" type="button" value="点击">
var obj = {
info: "This is some information",
check: function(){
// 扩展到jQuery原型上后,这里的this表示当前jQuery对象
this.prop("checked", true);
return this;
},
isEmpty: function(){
return !$.trim( this.val() );
}
};
// 将对象obj的属性和方法扩展到jQuery的原型对象上,以便于jQuery实例对象调用。
$.fn.extend( obj );
$("#btn").click(function(){
if( $("#name").isEmpty() ){
alert("姓名不能为空!");
return false;
}
$("[name=opt]").check( ); // 全选复选框
alert( $("body").info ); // This is some information
});
jQuery.globalEval()
var goo = 'goo';
(function() {
var foo = 'foo';
// eval的作用域是当前作用域(在这里就是local也就是function作用域),
// 因此既能访问local也能访问global作用域
eval('alert(foo)'); // foo
eval('alert(goo)'); // goo
// globalEval的作用域为全局,即使它写在当前作用域内,也不能获取当前作用域内的变量。
$.globalEval('alert(goo)'); // goo
$.globalEval('alert(foo)'); // ReferenceError foo is not defined
})();
jQuery.grep()
var arr0 = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
var arr1 = jQuery.grep(arr0, function( n, i ) {
return ( n !== 5 && i > 4 );
});
console.log(arr1); // [1, 9, 4, 7, 3, 8, 6, 9, 1]
var arr1_opp = jQuery.grep(arr0, function(n, i) {
return (n !== 5 && i > 4);
}, true);
console.log(arr1_opp); // [1, 9, 3, 8, 6, 5]
jQuery.inArray()
var arr = [ 4, "Pete", "8", "John" ];
jQuery.inArray( "John", arr ); // 3
jQuery.inArray( 4, arr ); // 0
jQuery.inArray( "Karl", arr ); // -1 不存在
jQuery.inArray( 8, arr ); // -1 严格匹配 指定的8为number,而数组中8为字符串
jQuery.inArray( "Pete", arr, 2 ); // -1 指定了从索引为2的位置开始查找,而Pete索引为1。
jQuery数据类型判断
jQuery.isArray()
jQuery.isArray([]); // true
jQuery.isArray($('div')); // false
function argumentsNotArrayTest(a,b,c) {
console.log(arguments);
return $.isArray(arguments);
}
argumentsNotArrayTest(1,2,3);
// [1, 2, 3]
// false
jQuery.isEmptyObject()
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false
var num1 = new Number(1);
console.log(num1); // Number {[[PrimitiveValue]]: 1}
$.isEmptyObject(num1); // true
jQuery.isFunction()
jQuery.isFunction(console); // false
jQuery.isFunction(console.log); // true
jQuery.isFunction(document); // fasle
jQuery.isFunction(document.getElementById); // true
var objs = [
function() {},
{ x: 15, y: 20 },
null,
NaN,
"function"
]
$.each(objs, function(i) {
var isFunc = jQuery.isFunction(objs[i]);
console.log(isFunc);
});
// true
// false
// false
// false
// false
jQuery.isNumeric()
// true (numeric)
$.isNumeric( "-10" )
$.isNumeric( "-10." )
$.isNumeric( "0" )
$.isNumeric( 0xFF )
$.isNumeric( "0xFF" )
$.isNumeric( "8e5" )
$.isNumeric( "3.1415" )
$.isNumeric( +10 )
$.isNumeric( 0144 )
// false (non-numeric)
$.isNumeric( "-10.." )
$.isNumeric( "-0x42" )
$.isNumeric( "7.2acdgs" )
$.isNumeric( "" )
$.isNumeric( {} )
$.isNumeric( NaN )
$.isNumeric( null )
$.isNumeric( true )
$.isNumeric( Infinity )
$.isNumeric( undefined )
jQuery.isPlainObject()
$.isPlainObject(document.location); // false
jQuery.isPlainObject(window); // false
jQuery.isPlainObject(window.location); // false
jQuery.isPlainObject({}); // true
jQuery.isPlainObject(new Object()); // true
jQuery.isPlainObject("test"); // false
jQuery.isWindow()
$.isWindow( window ); // true
jQuery.isXMLDoc()
$.isXMLDoc(document.body); // false
jQuery.type()
$.type( undefined ) // "undefined"
$.type() // "undefined"
$.type( window.notDefined ) // "undefined"
$.type( null ) // "null"
$.type( true ) // "boolean"
$.type( new Boolean() ) // "boolean"
$.type( 3 ) // "number"
$.type( new Number(3) ) // "number"
$.type( "test" ) // "string"
$.type( new String("test") ) // "string"
$.type( function(){} ) // "function"
$.type( [] ) // "array"
$.type( new Array() ) // "array"
$.type( new Date() ) // "date"
$.type( new Error() ) // "error" // as of jQuery 1.9
$.type( /test/ ) // "regexp"
jQuery.makeArray()
var divNodeList = document.getElementsByTagName("div");
var divArray = $.makeArray(divNodeList);
console.log(divArray[0].className); // input-group
$.isArray(divNodeList); // false
$.isArray(divArray); // true
var $ul=$('ul');
var ulArray = $.makeArray($ul);
$.isArray($ul); // false
$.isArray(ulArray); // true
jQuery.merge()
$.merge([0, 1, 2], [2, 3, 4]); // [ 0, 1, 2, 2, 3, 4 ]
$.merge([3, 2, 1], [4, 3, 2]); // [ 3, 2, 1, 4, 3, 2 ]
var arr1 = [1, 10, 100];
var arr2 = $.merge(arr1, [2, 20, 200]);
arr1 === arr2; // true
// 同样适用于类数组 但是并不会转化为数组,真实类型受第一个参数影响。
var $ul = $('ul');
var ulArray = $.merge([], $ul);
$.isArray(ulArray); //true
var ulArrayTest = $.merge($('h6'), $ul);
$.isArray(ulArrayTest); //false
jQuery.now()
var num1 = $.now(),
num2 = (new Date).getTime();
console.log(num1); // 1472442549526
console.log(num2); // 1472442549526
jQuery.parseHTML()
var str = "hello, <b>my name is</b> jQuery.",
html = $.parseHTML(str);
// 查看解析后的信息
console.log(html); // [text, b, text]
console.dirxml(html); // ["hello, ", my name is, " jQuery."]
// 遍历输出其节点信息
$.each(html, function(i, el) {
console.log(i, el.textContent, el.nodeName);
});
// 索引 textContent nodeName
// 0 "hello, " "#text"
// 1 "my name is" "B"
// 2 " jQuery." "#text"
// "<\/script>" 中"/"需要转义一下
var jsTest = 'Hello,<b>jQuery</b><script>alert("执行脚本代码");</script>';
var domNoJs = $.parseHTML(jsTest);
var domWithJs = $.parseHTML(jsTest, true);
console.log(domNoJs); //[text, b]
console.log(domWithJs); // [text, b, script]
console.dirxml(domNoJs); // ["Hello,", <b>jQuery</b>]
console.dirxml(domWithJs); // ["Hello,", <b>jQuery</b>, <script>alert("执行脚本代码");</script>]
// 未指定keepScripts时,脚本信息被忽略了。
jQuery.parseJSON()
var person = jQuery.parseJSON( '{ "name": "John" }' );
person.name === "John"; // true
在jQuery 1.9之前,如果传递给$.parseJSON一个空字符串,null, 或者 undefined,,将返回null,而不是抛出一个错误,即使这些都不是有效的JSON。 从jQuery 3.0 开始,$.parseJSON已经不推荐使用。要将字符串解析成JSON对象,请使用原生的JSON.parse方法来代替。
jQuery.parseXML()
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml );
console.dirxml(xmlDoc);
// 结果:
#document
<rss version="2.0">
<channel>
<title>RSS Title</title>
</channel>
</rss>
jQuery.proxy()
var zs = {
name: '张三',
sex: '男',
introduce: function(a, b) {
console.log('我叫', this.name, ',性别:', this.sex, ',我知道:', a, '*', b, '=', a * b);
}
}
// 直接调用
zs.introduce(1, 1); // 我叫 张三 ,性别: 男 ,我知道: 1 * 1 = 1
var ww = { name: '王五', sex: '男' };
ww.introduce = jQuery.proxy(zs.introduce, ww, 2331, 12320);
// 代理调用foo()函数,此时introduce方法内部的this指向新对象ww
ww.introduce(); // 我叫 王五 ,性别: 男 ,我知道: 2331 * 12320 = 28717920
ww.introduce1 = jQuery.proxy(zs.introduce, ww);
ww.introduce1(1234,5678); // 我叫 王五 ,性别: 男 ,我知道: 1234 * 5678 = 7006652
<p><button id="test" name='button-test'>Test</button></p>
<p id="log"></p>
var john = {
name: "John",
test: function() {
$( "#log" ).append( this.name );
$( "#test" ).off( "click", john.test ); // 点击后取消绑定
}
};
$( "#test" ).on( "click", $.proxy( john, "test" ) );
// 点击后显示John
// 如果click绑定事件写为$( "#test" ).on( "click", john.test) ); 则显示为id为test的button的name属性值:button-test
$( "#test" ).on( "click", john.test) ); // button-test
jQuery.trim()
var str = " lots of spaces before and after ";
str; // " lots of spaces before and after "
$.trim(str); // "lots of spaces before and after"
jQuery.unique()
// html
/*
<div>There are 6 divs in this document.</div>
<div></div>
<div class="dup"></div>
<div class="dup"></div>
<div class="dup"></div>
<div></div>
*/
var divs = $("div").get(); // unique() must take a native array
// add 3 elements of class dup too (they are divs)
divs = divs.concat($(".dup").get());
divs.length; // 9
divs = jQuery.unique(divs);
divs.length; // 6
console.dir(divs);
/*
[
<div>There are 6 divs in this document.</div>,
<div></div>,
<div class="dup"></div>,
<div class="dup"></div>,
<div class="dup"></div>,
<div></div>
]
*/