jQuery Custom Selector JQuery自定义选择器

本文介绍了JQuery中选择器的基础用法及如何创建自定义选择器,包括不含参数与带参数的选择器,并提供了具体的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是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');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值