Tag Archive jQuery

Byphunsanit

jQuery plugin แบบง่ายๆ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>basic jQuery plugin By Pitt Phunsanit</title>
</head>
<body>
<ul id="demo">
</ul>
<script>
/* jQuery Plugin Template */
(function($){
    /* $.fn.ชื่อ plugin */
    $.fn.instead = function(options){
        /* ค่า default ถ้าไม่ส่งมา */
        var settings = $.extend({
          id:"instead",
          background:"green"
        }, options);
        /* ทำงาน
        - อ้างถึง selected โดยใช้ this
        - ใช้ตัวแปรตามรูปแบบ settings.ตัวแปร
        */
        this.append('<li id="'+settings.id+'" style="background:'+settings.background+'">id = '+settings.id+'</li>');
        /* Maintaining Chainability */
        return this;
    };
})( jQuery );
</script>
<script>
$(function(){
    $('#demo')
    /* default */
    .instead()
    /* ปรับแต่ง */
    .instead({id:"customID" ,background:"yellow"})
    .instead({id:"customID2" ,background:"red"})
    /* test chainability */
    .css('color', 'white');
});
</script>
</body>
</html>