---
title: "jquery中钩子函数总结——jquery的另类扩展"
author: "renzhen"
date: "2012-08-08T16:45:04Z"
tags: []
categories: ["Web前端"]
slug: "jquery-jquery"
draft: false
lastmod: "2012-08-08T16:43:08Z"
id: 1625452
url: "https://renzhen.iteye.com/blog/1625452"
---

前段时间在网站看到一篇jquery的文章：[12款强大的jQuery选择器](http://sd.csdn.net/a/20120329/313673.html)，顿时被jquery的强大的扩展吸引，而jquery也同时支持css、val等操作的扩展，虽然网上介绍jquery插件开发的文章多如牛毛，但是完整介绍jquery中这部分扩展实现的却不多，于是想整理这一块的内容，今天在一篇国外blog找到这一块资料，讲的很详细,原文地址：<http://blog.rodneyrehm.de/archives/11-jQuery-Hooks.html>。下面是我对这篇文章重点做一个整理。
   jquery中如下函数有钩子函数，可以对函数属性进行自定义操作。它们分别是<span style="color:red"> attr(), prop(), val() 和css()</span>，同时还可以<span style="color:red">对selector的伪类实现自定义</span>。

  1. attr() 和 prop() 函数 （jquery 1.6以上）
   $.attrHooks  和 $.propHooks
   
```js

$.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()函数 （jquery 1.6以上）
  $.valHooks
  
```js

$.valHooks.div = {
  get: function(elem) {
    return $(elem).data('foobar');
  },
  set: function(elem, value) {
    $(elem).data('foobar', value);
  }
};
  
```


  3.css()函数 （jquery 1.4.3以上）
  $.cssHooks
  
```js

$.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 伪类 （jquery 1.3以上）
  $.expr.filters 或者 $.expr 都可以 ，貌似是用$.expr更常用
  
```js

$.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）
>