严格来说是自定义伪类选择器,不过也相当有意思了。
昨天我学习其中一个 jquery lazy load 源码的时候,看到末尾这么写的。
/* Custom selectors for your convenience. 译: 提供自定义选择方便你使用。 */
/* Use as $("img:below-the-fold").something() or 译: 你可以这样使用 $("img:below-the-fold").something() 或 */
/* $("img").filter(":below-the-fold").something() which is faster 译: $("img").filter(":below-the-fold").something() 这样更快 */
// 简单翻译了下不知道准不准确。。
$.extend($.expr[":"], {
"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
"in-viewport" : function(a) { return $.inviewport(a, {threshold : 0}); },
/* Maintain BC for couple of versions. */
"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); },
"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); }
});
好神奇的说,有木有。。
虽然之前也有简单的看过 jQuery 源码,可是 Sizzle 选择器引擎部分我直接跳过了,所以完全没注意到这块功能。
出于好奇心,当然要去学习下怎么自定义选择器。
翻了下百度谷歌,只找到一篇靠谱的中文博客。。看样子这东西确实冷门啊。。仔细想想确实没多大必要自定义。。
不过以学习为目标,多学点总是好的。
大家可以去看下这篇文章《jQuery Custom Selector JQuery自定义选择器》
基本格式:
$.expr[‘:‘].test = function(obj, index, meta, stack) {
/* obj - is a current DOM element 当前DOM元素
index - the current loop index in stack 当前元素在stack中的索引,
meta - meta data about your selector !!! 用来存参数值,详见带参数的自定义选择器。
stack - stack of all elements to loop 选择器所选中的元素集。
Return true to include current element 返回 true 就包含当前元素
Return false to explude current element 返回 false 就抛弃当前元素
*/
};
调用方法:
$(‘.someClasses:test‘).doSomething();
带参数调用:
$(‘.someClasses:test(argument)‘).doSomething();
$(‘.someClasses:test("arg1, arg2")‘).doSomething();
$(".someClasses:test(‘arg1, arg2‘)").doSomething();
还记得刚才 meta 参数么?
例如这样调用:
$(‘.someClasses:test(argument)‘).doSomething();
meta 就会得到如下格式的数组:
[
‘:test(argument)‘, // full selector 整个自定义选择器
‘test‘, // only selector 自定义选择器名称
‘‘, // quotes used 使用了什么引号(很明显这里没有)
‘argument‘ // parameters 参数
]
例如调用:
$(‘.someClasses:test("arg1, arg2")‘).doSomething();
meta 就会得到如下格式的数组:
[
‘:test("arg1, arg2")‘, // full selector 整个自定义选择器
‘test‘, // only selector 自定义选择器名称
‘"‘, // quotes used 使用了什么引号(这里用的是双引号)
‘arg1, arg2‘ // parameters 参数
]
那我们来写个简单的选择器,当作练习吧。
就写个刚才那个选择器把,带参数好了。
$("a:test(haha)");
自定义选择器代码为:
$.expr[‘:‘].test = function(obj, index, meta, stack) {
var txt = obj.innerHTML,
key = meta[3];
return txt.indexOf(key) > -1;
};
// 测试
$(‘#navList a:test(JavaScript)‘).each(function () {
console.log(this.innerHTML);
});
点击右侧运行看看。。
没啥技术含量,不过确实是有意思的技巧。
其他参考资料:
http://www.cnblogs.com/webfpc/archive/2009/11/22/1605302.html
http://jquery-howto.blogspot.com/2009/06/custom-jquery-selectors.html
http://jquery-howto.blogspot.com/2009/06/jquery-custom-selectors-with-parameters.html
原文地址:http://www.cnblogs.com/52cik/p/jquery-custom-selector.html