jQuery实用函数用法总结(2)
$.param(params)把传入的jquery对象或javascript对象转换成字符串形式。
$(document).ready(function(){ personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; $("button").click(function(){ $("div").text($.param(personObj)); }); });
结果:firstname=John&lastname=Doe&age=50&eyecolor=blue
10.一些判断函数
$.isArray(o) 如果o是javascript数组,则返回true,如果是类似数组的jquery对象数组,返回false
$.isEmptyObject(o) 如果o是不包含属性的javascript对象,则返回true
$.isFunction(o) 如果o是javascript函数就返回true
$.isPlainObject(o) 如果o是通过{}或new Object()创建的对象,则返回true
$.isXMLDoc(node) 如果node是XML文档或者是XML文档中的节点,则返回true
11.判断一个元素是否包含在另外一个元素中
$.contains(container, containee)第二个参数是被包含
$.contains( document.documentElement, document.body ); // true $.contains( document.body, document.documentElement ); // false
12.把值存储到某元素上
$.data(element, key, value)第一个是javascript对象,第二、第三个是键值。
//得到一个div的javascript对象 var div = $("div")[0]; //把键值存储到div上 jQuery.data(div, "test",{ first: 16, last: 'pizza' }) //根据键读出值 jQuery.data(div, "test").first jQuey.data(div, "test").last
13.移除存储到某元素上的值
<div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div> var div = $( "div" )[ 0 ]; //存储值 jQuery.data( div, "test1", "VALUE-1" ); //移除值 jQuery.removeData( div, "test1" );
14.绑定函数的上下文
jQuery.proxy( function, context)返回一个新的function函数,上下文是context。
$(document).ready(function(){ var objPerson = { name: "John Doe", age: 32, test: function(){ $("p").after("Name: " + this.name + "<br> Age: " + this.age); } }; $("button").click($.proxy(objPerson,"test")); });
以上,点击按钮,执行的是test方法,不过test方法的上下文做了设置。
15.解析JSON
jQuery.parseJSON( json )第一个参数json的类型是字符串。
var obj = jQuery.parseJSON( '{ "name": "John" }' ); alert( obj.name === "John" );
16.表达式求值
有时候,希望一段代码在全局上下文中执行,可以使用jQuery.globalEval( code )。code的类型是字符串。
function test() { jQuery.globalEval( "var newVar = true;" ) } test();
17.动态加载脚本
$(selector).getScript(url,success(response,status))用来动态加载js文件,第一个参数是js的文件路径,第二个参数可选,表示获取js文件成功的回调。
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { console.log( data ); // Data returned console.log( textStatus ); // Success console.log( jqxhr.status ); // 200 console.log( "Load was performed." ); });
相信本文所述对大家的jQuery程序设计有一定的借鉴价值。