自定义JS控件-简单示例

1、  业务需求: 制作 一个按钮对象,然后 像 winfrom  那样调用 就可以了:

首先 我们新建一个 MyControls的 JS文件:(插入如下代码)

//这里运用的面向对象的思想 ,新建了一个按钮对象 
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();  //隐藏 当前控件
            };
            
        }

接下来我们 怎么用的这个 对象呢?

首先,我们先导入 jquery的插件

然后我们要引入 这个 文件的路径:

接下来写入 button 的样式:

<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页面内 写下:

<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>

保存,打开,运行就能看到结果了。

原文地址:https://www.cnblogs.com/albert-struggle/p/4380148.html