zhangyang0 2012-08-08
前段时间在网站看到一篇jquery的文章:12款强大的jQuery选择器,顿时被jquery的强大的扩展吸引,而jquery也同时支持css、val等操作的扩展,虽然网上介绍jquery插件开发的文章多如牛毛,但是完整介绍jquery中这部分扩展实现的却不多,于是想整理这一块的内容,今天在一篇国外blog找到这一块资料,讲的很详细,原文地址:http://blog.rodneyrehm.de/archives/11-jQuery-Hooks.html。下面是我对这篇文章重点做一个整理。
jquery中如下函数有钩子函数,可以对函数属性进行自定义操作。它们分别是attr(),prop(),val()和css(),同时还可以对selector的伪类实现自定义。
1.attr()和prop()函数(jquery1.6以上)
$.attrHooks和$.propHooks
$.propHooks.open = {
get: function(elem) {
if (elem.nodeName.toLowerCase() !== 'details') {
// abort for non-<detail> elements
return undefined;
}
// return the open-state as a boolean
// (.prop() is supposed to return a boolean)
return !!$(elem).details('is-open');
},
set: function(elem, value) {
if (elem.nodeName.toLowerCase() !== 'details') {
// abort for non-<detail> elements
return undefined;
}
// convert value to a boolean and pass it to the plugin
return $(elem).details(!!value);
}
};
$.attrHooks.open = {
get: function(elem) {
if (elem.nodeName.toLowerCase() !== 'details') {
// abort for non-<detail> elements
return undefined;
}
// convert the plugin's boolean to the string "open" or empty-string
// (.attr() is supposed to return the actual value of the attribute)
return $(elem).details('is-open') ? 'open' : '';
},
set: $.propHooks.open.set
};2.val()函数(jquery1.6以上)
$.valHooks
$.valHooks.div = {
get: function(elem) {
return $(elem).data('foobar');
},
set: function(elem, value) {
$(elem).data('foobar', value);
}
};3.css()函数(jquery1.4.3以上)
$.cssHooks
$.cssHooks.boxSizing = {
set: function(elem, value) {
if (value === 'border-box' && $('html').is('.ie6, .ie7')) {
// fix <IE8
elem.style.behavior = 'url(/scripts/boxsizing.htc)';
}
elem.style.boxSizing = value;
}
};4.自定义selector伪类(jquery1.3以上)
$.expr.filters或者$.expr[':']都可以,貌似是用$.expr[':']更常用
$.expr.filters.local = function(elem, i, match, array) {
if (elem.nodeName.toLowerCase() !== 'a') {
// abort for non-<a>
return false;
}
// use jQuery's URL denormalization
var href = $(elem).attr('href');
if (!href || href.substring(0, 1) === '#') {
// skip anchors
return false;
}
if (href.substring(0, 1) === '/') {
// authority-relative URL
return true;
}
// matching host?
var host = ('//' + location.host + '/')
.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'));
return !!href.match(new RegExp(host, 'i'));
}
$.extend($.expr[':'],
{
loaded: function(el)
{
return $(el).data('loaded');
}
}最后,原文作者还提到一些是用这些扩展的注意事项,具体内容可以查看原文。其中特别提一下对自定义selector伪类的使用有一个陷阱。
一旦在selector中使用自定义的伪类,那么jquery就不能使用系统原生的querySelector()函数来优化执行这个selector,而且伪类会对所有元素进行筛选,使用时最好去掉不必要的元素,比如:(a:foo要好于:foo)