jQuery Custom Selector JQuery自訂選取器

來源:互聯網
上載者:User

標籤:http   color   os   io   cti   ar   div   line   

什麼是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‘);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.