使用jQuery在對象中緩衝選取器的簡單方法,jquery選取器

來源:互聯網
上載者:User

使用jQuery在對象中緩衝選取器的簡單方法,jquery選取器

 當使用像jQuery這樣的庫時,開發人員通常會使用選取器來訪問和操作DOM中的元素。當一個選擇在頁面上被反覆的訪問時,把它緩衝起來以獲得更好的效能是個不錯的想法。

讓我們看一個例子,
 

jQuery(document).ready(function() {  jQuery('#some-selector').on('hover', function() {    jQuery(this).fadeOut('slow').delay(400).fadeIn();    console.log(jQuery(this).text());  });   jQuery('#another-element').on('hover', function() {    jQuery(this).slideUp();  });   jQuery('#some-selector').on('click', function() {    alert('You have clicked a featured element');  });   jQuery('#another-element').on('mouseout', function() {    jQuery(this).slideUp();  });});

也許你已經注意到,ID ‘some-selector' 和 ‘another-element' 在上面的程式碼片段中被提到了兩次。通過把這些選取器儲存到變數裡,可以使他們能被複用,並且避免了重複選擇操作。


當你開始在你的jQuery代碼裡積攢出各種各樣的選取器時,你就能領會到在對象中緩衝選取器 – 以索引值對的形式 – 是多麼美好。這使得你更容易在指令碼中的任何地方訪問它們,並且維護這些選取器也是輕而易舉事。

緩衝選取器後,改進過的代碼會像這樣,
 

var someNamespace_Dom = {  someSelector : 'jQuery("#some-selector")',  anotherElement: 'jQuery("#another-element")',}; jQuery(document).ready(function() {  someNamespace_Dom.someSelector.on('hover', function() {    jQuery(this).fadeOut('slow').delay(400).fadeIn();    console.log(jQuery(this).text());  });  someNamespace_Dom.anotherElement.on('hover', function() {    jQuery(this).slideUp();  });  someNamespace_Dom.someSelector.on('click', function() {    alert('You have clicked a featured element');  });  someNamespace_Dom.anotherElement.on('mouseout', function() {    jQuery(this).slideUp();  });});

由於選取器已經被緩衝到變數中,DOM 樹不再需要被重複遍曆來尋找被操作的元素。‘someNamespace_Dom' 對象可以被用來添加更多索引值對,使得維護工作很輕鬆。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.