显示标签为“jquery”的博文。显示所有博文
显示标签为“jquery”的博文。显示所有博文

2011年11月7日星期一

jQuery 1.7 事件绑定函数

jQuery 1.7 前几天发布了,新增了两个事件处理函数 .on() 和 .off() 分别用来绑定和解除事件。这两个函数可以取代之前版本中所有的事件处理函数。
现在事件绑定和解除更简单了,下面是新旧版本事件处理代码的对比:

$('a').bind('click', myHandler);
$('a').on('click', myHandler);

$('form').bind('submit', { val: 42 }, fn);
$('form').on('submit', { val: 42 }, fn);

$(window).unbind('scroll.myPlugin');
$(window).off('scroll.myPlugin');

$('.comment').delegate('a.add', 'click', addNew);
$('.comment').on('click', 'a.add', addNew);

$('.dialog').undelegate('a', 'click.myDlg');
$('.dialog').off('click.myDlg', 'a');

$('a').live('click', fn);
$(document).on('click', 'a', fn);

$('a').die('click');
$(document).off('click', 'a');


另外想说一下jQuery中的事件对象(Event Object):

jQuery的事件系统规范化了事件对象(根据W3C标准)。jQuery保证事件对象被传递给事件处理程序。大部分的属性从原来的事件中复制和规范化给新的事件对象。

jQuery保证下列属性是事件对象的成员,尽管它们中的一些值可能是undefined(依赖于具体的事件):

altKey, attrChange, attrName, bubbles, button, cancelable,
charCode, clientX, clientY, ctrlKey, currentTarget, data, detail,
eventPhase, fromElement, handler, keyCode, layerX, layerY,
metaKey, newValue, offsetX, offsetY, originalTarget,
pageX, pageY, prevValue, relatedNode, relatedTarget,
screenX, screenY, shiftKey, srcElement, target,
toElement, view, wheelDelta, which


为了跨浏览器兼容,jQuery 对下列属性进行了规范化:

target
relatedTarget
pageX
pageY
which
metaKey


特别注意,并不是所有原始事件的属性都被复制给jQuery的事件对象。这时可以用 event.originalEvent 来获取原始事件对象。比如在HTML5文件拖放操作时需要用到drop事件的dataTransfer属性,可以像下面这样做:

$('body').on('drop',function(e){
var file = e.originalEvent.dataTransfer.files[0];//获取一组拖放文件中的第一个文件

reader = new FileReader();//创建FileReader对象来读取文件内容
reader.onload = function(e){//读取完成时将内容显示于body中
$('body').text(e.target.result);
};
reader.readAsText(file,'utf-8');//开始读取文件

//相当于同时调用e.stopPropagation() 和 e.preventDefault()
return false;//阻止事件冒泡和浏览器的默认行为
});

2011年8月20日星期六

jQuery.post()函数的使用方法

函数原型: jQuery.post( url, [data], [success(data, textStatus, jqXHR)], [dataType] )
参数说明:
url 请求发送的地址
data 随请求发送的一个关联对象或者一个字符串
success(data, textStatus, jqXHR) 指定请求成功时执行的一个callback函数
dataType 预期从服务器接收的数据类型. 默认: 智能判断 (xml, json, script, or html).

返回值类型:jqXHR

此函数是下面函数的简写形式

$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});


使用示例:

$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json")
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });


关于dataType参数的详细说明
期待从服务器返回的数据类型. 如果不指定, jQuery 将基于返回结果的MIME类型 (XML MIME 类型将产生 XML, in 1.4 JSON 将产生 一个 JavaScript 对象, in 1.4 script 将执行 script, and 其他将作为字符串返回)尝试推断它. 可用的类型 (和传递给 success callback 函数第一个参数最终的结果) 是:

"xml": 返回一个可以通过jQuery解析的 XML 文档 .

"html": 把 HTML 作为普通文本返回; included script tags are evaluated when inserted in the DOM.

"script": 将返回值作为 JavaScript对待并以普通文本方式返回. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.

"json": 将返回值作为 JSON 对待 并返回一个 JavaScript 对象. In jQuery 1.4 JSON 数据使用严格的方式解析; 任何格式异常的JSON 都被拒绝并抛出一个parse error. (更多关于正确的JSON格式请参考 json.org 网站.)

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

"text": 普通文本字符串.

多个以空格分隔的值: 从 jQuery 1.5, jQuery 能够将从Content-Type头中得到的dataType转换为你需要的其他类型 . 例如,如果你想将一个文本返回值作为XML对待,使用 "text xml" 作为 dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

2011年5月6日星期五

jQuery获取window、document、dom元素的高度和宽度函数分析

以下为获取高度或宽度函数的jQuery源代码

// 创建jQuery.height(size) jQuery.width(size)
//调用each方法创建两个相似的函数
jQuery.each([ "Height", "Width" ], function( i, name ) {

var type = name.toLowerCase();

jQuery.fn[ type ] = function( size ) {

var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}

if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}

// 获取window对象的高度或宽度 ($(window).width() ) 实际上是当前可见区域的高度或宽度
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
// 以上英文的意思是依赖于Quirks 或 Standards 文档模式来使用
// document.documentElement (实际上就是元素) 或 document.body
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;

// 获取整个文档对象(document)的宽度或高度
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);

// 获取DOM元素的高度或宽度
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );

return jQuery.isNaN( ret ) ? orig : ret;

// 设置DOM元素的高度或宽度 (当没有单位时默认为像素值)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};

});

jQuery(window).height()代表了当前可见区域的大小,而jQuery(document).height()则代表了整个文档的高度,可视具体情况使用
注意当浏览器窗口大小改变时(如最大化或拉大窗口后) jQuery(window).height() 随之改变,但是jQuery(document).height()是不变的。