5
2010
วิธีสร้าง Plugin ของ jQuery
Howto createing a plugin for jQuery.
วันนี้มาดูวิธีการสร้าง Plugin สำหรับ jQuery แบบง่ายๆกันนะครับ หลายๆคนก็คงเคยโหลด Plugin ของ Developer คนอื่นๆมาใช้กันบ้างแล้ว แล้วถ้าเราจะทำใช้เองบ้างละ บอกได้คำเดียวครับ ง่ายมากๆ มาลองกันเลย
ผมจะทดลองเขียน Plugin สำหรับการกำหนด Style Sheet ( css ) ให้กับ Tag ใดๆที่เราต้องการนะครับ คือจะทำการเปลี่ยน สี ทั้งหมดให้กับ DIV ที่เราต้องการจะเปลี่ยนนะครับ มาดู code กัน
ตัวอย่างนี้เป็นการสร้าง Function แบบธรรมดาเพื่อนำมาเรียกใช้งาน ( ดู code ด้านล่างต่อเพื่อดูความแตกต่างของ code นะครับ )
1 2 3 4 5 6 7 8 9 10 11 | function applyColors(elems) { $(elems).css({ color: config.color, backgroundColor: config.bgColor, borderColor: config.bdColor }); } // Call it: var myElems = $('div.something'); applyColors(myElems); |
จาก code ด้านบนลองมาดู code นี้กันบ้างครับ ว่าการสร้าง plugin ของ jquery นั้นง่ายแค่ใหน
เราสามารถเขียน code ด้านล่างนี้แล้ว save ให้เป็น jquery.myplugin.js แต่เวลานำไปใช้จะต้องเรียก core หลักก่อนนะครับ
1 2 3 4 5 6 7 8 9 10 | jQuery.fn.applyColors = function( { return this.css({ color: config.color, backgroundColor: config.bgColor, borderColor: config.bdColor }); }; // Call it: $('div.something').applyColors(); |
จะเห็นความแตกกันกันตรงที่เราสามารถจะ ทำการเรียกใช้ function นั้นๆที่เราสร้างขึ้นมาได้เลยครับ
โดยต่อจาก $() ได้เลย เห็นใหมครับง่ายมากๆ
Related Posts
Tags
Facebook Development
Google+ Page
Categories
- HTML5 & CSS3 (8)
- jQuery 1.4 (9)
- jQuery 1.5 (6)
- .data (1)
- jQuery 1.6 (3)
- .data (1)
- jQuery 1.7 (4)
- Events (1)
- jQuery Mobile (3)
- jQuery UI (3)
- Mobile (1)
- News (8)
- Others (28)
- Plugin (15)
- The basics of jQuery (9)
- Tips (13)
- คู่มือการใช้งาน jQuery ฉบับ ภาษา ไทย (30)
- Ajax (4)
- Attributes (1)
- Core (1)
- Deferred (3)
- Effects (7)
- Events (3)
- Manipulation (2)
- Selectors (5)
- Traversing (2)
- Utilities (2)

An article by







