A useful tag function

Source: Internet
Author: User
Tags event listener extend json

The tag function mentioned in the article title is based on jquery, so it's important to introduce jquery files before you use them. This function is primarily used to dynamically create labels, and to obtain the corresponding DOM object for the created tag. Note: This function is not encapsulated in the form of jquery plug-ins, if you want to transform into a jquery plug-in form, you need to do it yourself.

The 1.TAG function requires some other tool functions, as shown in the code below. For these tool functions, I mainly create a new file named Util.js to save.

/** * Define namespace util */util = {};

/** * Test JS for loading success */util.test = function () {jsout ("Util.js is working");}; /** * Console Output */function Jsout (str) {console.debug (str)}/** * Search by ID * * Function FindByID (ID) {return $ ("
# "+id+" "); }/** * Create a namespace.
 The <br> * namespace is a global variable.
    * @param ns namespace, such as Mgr.system.errorcode */util.namespace = function (ns) {var names = Ns.split (".");
    var upperns = window;
        $.each (names, function (i, name) {if (upperns[name] = = undefined) {Upperns[name] = {};
    } upperns = Upperns[name];
});
};

NS = Util.namespace; /** * Determines whether a string is undefined or null or "" * @param str * @returns {Boolean} */util.isnullorempty = function (str) {retur n str = = undefined | | str = = NULL | |
$.trim (str) = = "";

};
Util.notnullorempty = function (str) {return!util.isnullorempty (str);};

/** * is an integer * @param num * @returns */util.isinteger = function (num) {return/^\d+$/.test (num);}; /** * Parses a string intoJSON Object * @param JSON * @returns */Util.parsejson = function (JSON) {return eval ("(" +json+ ")");}; /** * determine if double label * @param tag * @returns {Boolean} */Util.isdoubletag = function (tag) {var singletags = ["br", "Inpu
    T "," IMG "];
return Singletags.indexof (TAG) < 0;

};
    /** * Generate Random ID */util.id = function () {var id = math.random () + "";
Return id.substring (2);
 };

2. With the above tool function, the code of tag can be given successfully. I actually created a new file named Core.js to save, the code is as follows:

namespace core = {};
        function Tag (params) {if (params = = undefined) {throw ("parameter cannot be empty when creating Tag object");
    Return
        } if (typeof params = = "string") {var tag = params;
        params = {};
    Params.tag = tag;
    }//If no ID is specified, a random ID is generated if (Util.isnullorempty (params.id)) {params.id = Util.id (); }//The properties listed here can be specified directly in the tag object.
    Properties that are not listed need to be specified in their attrs var directattrs = [' ID ', ' class ', ' style ', ' type ', ' value ', ' Width ', ' selected '];
        if (Util.notnullorempty (params["CLS"])) {params["class"] = params["CLS"];
    Delete params.cls;
    }//Copy This property value to the Params.attrs object var attrs = {};
        $.each (directattrs, function (i, a) {if (Util.notnullorempty (Params[a])) {Attrs[a] = Params[a];
    }
    });
    if (params.attrs = = undefined) {params.attrs = {};

    } $.extend (Params.attrs,attrs);
    /* * html, text, innerHTML attributes are parsed as items */var items = []; var innerhtmlfields = ["html", "TEXT "," innerHtml "];
        $.each (Innerhtmlfields, function (i, f) {if (Params[f]) {Items.push (params[f]);
    }
    });
    if (!params.items) {params.items = [];
        } if (!$.isarray (Params.items)) {var arr = [];
        Arr.push (Params.items);
    Params.items = arr;
    } $.merge (items, params.items);

    Params.items = items;

    Copies the properties of the params to the This object $.extend (this, params);
    /* Bind event listener **/var listeners = params.listeners; for (Var listener in listeners) {if (listener) {$ ("body"). Delegate ("#" + params.id, listener, listeners
        [Listener]);

    }
    }; /* If Containerid or container is specified, insert the created label into the DOM **/if (Util.notnullorempty (Params.containerid)) {FindByID (params.co
    Ntainerid). Append (this.tohtml ());
    }else if (Util.notnullorempty (Params.container)) {$ (Params.container). Append (this.tohtml ());
    };
/* Identify yourself as an instance of the tag object **/this._istaginstance = true;
} $.extend (Tag.prototype, {    /*****************************************************public*************************************************** /Tohtml:function () {/* * Handling Special Properties */if (Util.notnullorempty (this.attrs["width"])
            ) {var width = this.attrs["width"];
            if (Util.isinteger (width)) {width + = "px";
            } if (Util.isnullorempty (this.attrs["style"])) {this.attrs["style"] = "";
            } this.attrs["Style"] + = "width:" + width;
        Delete this.attrs["width"];
        }/* * Assemble attribute String */var attrs = ""; for (Var attr in this.attrs) {if (this.attrs[attr]! = null) {attrs + = "" + attr + "=" + this.at
            trs[attr]+ "'";
        }/* * processing child elements */var items = This.items;
        var innerHtml = ""; $.each (items, function (I, item) {if (typeof item = = ' ObjecT ') {if (!item._istaginstance) {//ordinary object, not tag instance item = new tag (item);//Create a parameter with this object
        A tag object}} innerHtml + = Item + "";//Auto-call item.tostring ();

        });
        /* * Generate HTML */var tag = This.tag;
        var html = "";
        if (Util.isdoubletag (tag)) {html = "<" + tag + attrs + ">" + innerhtml+ "</" + tag+ ">";
        }else{html = "<" + tag + attrs + "/>";
        } this._html = html;
    return this._html;
    }, Insert:function (tag) {This.items.push (tag);
    },/** * Overrides the ToString method */Tostring:function () {return this.tohtml ();
    },/** * @returns insert tag into the DOM, you can call this method to get the corresponding jquery object */$:function () {return FindByID (this.id); 
    },/** * Gets the attribute value * @param attrname */attr:function (attrname) {return this.attrs[attrname];

}

}); Core. tag = tag;

3. Use demonstration (provided that jquery files are introduced and the two files mentioned above)

  var tag = new core. Tag ({
        tag: "div",//Create a div tag
        containerid: ",//or container (a jquery selector). If you specify this property, The tag object automatically inserts the DOM object represented by Containerid after initialization, and acts as its last child node. For example, you can specify the id attribute value of the body tag, then the resulting div tag will be inserted into the body
        HTML: "ss",//or text, or innerHtml, the text of the generated div tag
        cls: ',//equals to Attrs["Class"],
        listeners:{//listener. Can listen for jquery supported events
            Click:function () {},
            focus:function () {}
        },
        attrs:{
            ID: ',//Specify ID attribute value
            " Class ': ',//Specify class attribute value
            style: ',
            type: ',
            value: ',
            //The above attribute can be directly defined in the tag object
            like tag, html .....//any other Attributes
        },
        items:[new tag ("div"), {tag: ' div '}, ' hello ']//child element Array, An array element can be either a tag object or a configuration object of a tag object or a normal string,
  })
  tag.tohtml ();//Print the result and know what it is
  tag.attr ("Attrname"); Print the results and know what it is.
  tag.$ ();//Gets the DOM object for the tag, and the console prints out the result to know what it is, for example, Console.log (tag.$ ())

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.