2014-11-22 46 views
0

我遇到了jQuery範圍的問題,我想。我正在嘗試使用經典的jquery「greenify」教程插件,並且已經調整它以將所有錨鏈接的顏色更改爲由其各自的data-color屬性指定的顏色。但是,顏色始終是紅色的。有人能告訴我我做錯了什麼嗎?如何編寫一個與多個元素一起工作的jquery插件?

HTML:

<a data-color="red">Red</a> 
<a data-color="yellow">Yellow</a> 
<a data-color="black">Black</a> 

JS:

(function ($) { 
    $.fn.colify = function() { 
     this.css("color", $(this).data('color')); 
     return this; 
    }; 
}(jQuery)); 
$('a').colify(); 

JS FIDDLE:http://jsfiddle.net/y4589gy2/

回答

2

我suggeset:

(function ($) { 
    $.fn.colify = function() { 
     // return the results of calling the methods for chaining, 
     // note that 'this' refers to the jQuery collection (not DOM nodes): 
     return this.css("color", function() { 
      // using the anonymous function available to 'css()', 
      // this here refers to the individual DOM node over 
      // which jQuery is iterating in CSS(): 
      return $(this).data('color'); 

     }); 
    } 
})(jQuery); 
$('a').colify(); 

JS Fiddle demo

儘管你不需要調用jQuery的,或使用data(),在css()通話中,你可以簡單地使用HTMLElement.dataset訪問data-*屬性:

(function ($) { 
    $.fn.colify = function() { 
     return this.css("color", function() { 
      // this.dataset.color returns the attribute value from 'data-color', 
      // if that returns undefined (or a falsey value) 'black' is used instead: 
      return this.dataset.color || 'black'; 

     }); 
    } 
})(jQuery); 

JS Fiddle demo

this.getAttribute('data-color')可以用於代替this.dataset.colorJS Fiddle demo)的位置(可能有助於支持舊瀏覽器)。

參考文獻:

+0

感謝您的幫助。這很有趣,我從來不知道你可以傳遞一個函數作爲CSS方法的第二個參數。 '(函數($){ $ .fn.myplugin =功能(選件){ \t \t:一些更多的研究,我發現,對於較大的插件後,我可以開始與線插件獲得所需的結果return this.each(function(){//其餘的插件代碼在這裏...}); }; }(jQuery)); – kohloth 2014-11-24 15:29:25

相關問題