首页 > 代码库 > jQuery Custom Selector JQuery自定义选择器
jQuery Custom Selector JQuery自定义选择器
什么是JQuery的选择器呢,详见JQuery中的Selector: http://docs.jquery.com/Selectors
比如 $("div:contains(‘John‘)").css("text-decoration", "underline");的contains选择器等等
JQuery自定义选择器的基本语法:
$.expr[‘:‘].test = function(obj, index, meta, stack){
/* obj - is a current DOM element
index - the current loop index in stack
meta - meta data about your selector !!! 用来存参数值,详见带参数的自定义选择器。
stack - stack of all elements to loop
Return true to include current element
Return false to explude current element
*/
};
// Usage:
$(‘.someClasses:test‘).doSomething();
1.创建一个简单的自定义选择器(将返回"rel"标签不为空的元素)
$.expr[‘:‘].withRel = function(obj){
var $this = $(obj);
return ($this.attr(‘rel‘) != ‘‘);
};
// 应用:
$(‘a:withRel‘).css(‘background-color‘, ‘yellow‘);
效果见:http://custom-drupal.com/jquery-demo/custom-selectors/
2. 创建带参数的自定义选择器,通过meta来实现.
语法:
$(‘a:test(argument)‘);
//meta would carry the following info: meta的格式如下(meta[3]对应的值是argument)
[
‘:test(argument)‘, // full selector
‘test‘, // only selector
‘‘, // quotes used
‘argument‘ // parameters
]
$(‘a:test("arg1, arg2")‘);
//meta would carry the following info:
[
‘:test(‘arg1, arg2‘)‘, // full selector
‘test‘, // only selector
‘"‘, // quotes used
‘arg1, arg2‘ // parameters
]
实例:
$.expr[‘:‘].withAttr = function(obj, index, meta, stack){
return ($(obj).attr(meta[3]) != ‘‘);
};
应用:
$(‘a:withAttr(rel)‘).css(‘background-color‘, ‘yellow‘);