自定義JS控件-簡單示例

一、  業務需求: 製做 一個按鈕對象,而後 像 winfrom  那樣調用 就能夠了:javascript

首先 咱們新建一個 MyControls的 JS文件:(插入以下代碼)css

//這裏運用的面向對象的思想 ,新建了一個按鈕對象 
var button = function (ClientId) {  
            this.control = null;   //屬性: 按鈕對象的 本身
            this.id = null;          //按鈕對象的 id
            this.value = null;    //按鈕對象顯示的值
            this.click = null;      //按鈕對象的點擊事件
            //接下來是初始化, 全部 按鈕的屬性
            this.init = function () {
                this.id = ClientId;   //這個是頁面傳過來的id
                this.control = $("#" + ClientId);  //這是經過 id綁定控件
                var button_html = '<div href="#"  id="button_'+this.id+'"  class="button" > ' + this.value + '</div>';  // 這個是咱們要插入 的 html文件
                this.control.after(button_html);  
               //綁定點擊事件            
                $("#button_"+this.id+).unbind("click").bind("click",this.click);                                                                                                                       
                this.control.hide();  //隱藏 當前控件
            };
            
        }

接下來咱們 怎麼用的這個 對象呢?html

首先,咱們先導入 jquery的插件java

而後咱們要引入 這個 文件的路徑:jquery

接下來寫入 button 的樣式:web

<style type="text/css">       
   .button {
       padding: 10px 20px 10px 20px; border: medium solid #FF00FF; width:auto; height: 20px; float: left; background-color: #808080; font-family: 幼圓; font-size: large; font-weight: bold; 
    }
</style>

而後 ,接下來咱們 在  你的  web頁面內 寫下:ide

<div id="btn"></div>   //這裏 是咱們的要將 其改變成 按鈕
<script type="text/javascript">
 var btn_button = new button("btn");    //這裏是 new  一個按鈕的對象, 有沒有以爲 很是 像 winfrom  的開發
        btn_button.value = "一個按鈕";    //這裏是給他的屬性賦值
        btn_button.click = function () {   //這裏是 按鈕的點擊事件   
            alert("展現出來了·");
        }
        btn_button.init();                 //而後初始化 按鈕  ,注意!!!  初始化 必定要在 全部屬性 賦值完成後才執行
 </script>

保存,打開,運行就能看到結果了。this

相關文章
相關標籤/搜索