Home >Web Front-end >JS Tutorial >Sharing some tips for writing widgets with jQuery_jquery

Sharing some tips for writing widgets with jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:17:351288browse

1. When writing widgets, we generally need to bind some events. It is best to add the binding events of these widgets to the namespace of the current widget. If the same jQuery object is used with two widgets, and both widgets are bound to the same event name, problems may occur. When destroying the widget, it is also very convenient to remove the binding event. Just unbind (".namespace") is required.
2. When writing jQuery, because jQuery objects support continuous writing. For example: $(obj).css("height","20px").attr("title","abc")....
3. You can use the native method of javascript to avoid switch when writing .

Copy code The code is as follows:

switch(a)
{
case "aa":
 this._set_aa();
 break;
case "bb":
this._set_cc();
 break;
}


The above code can be replaced with the following code


Copy code The code is as follows: this["_set_" a]();

4. Try to cache jQuery objects, and various variable. This can improve the performance of the script
5. Use variables to cache this pointer. This can be minimized when the code is minimized.
6. It is best to give the css class a consistent name, and then define variables and save them. Use variables directly when using them, so even if the css name is adjusted, you only need to change the value of the variable cache. At the same time, the size of the code can also be reduced when minimized.
7. When setting Option, if an option is a complex object rather than a simple value object, it is best not to simply use this.options[key]=value. Before doing this, you need to compare the value with the value of the previous option. Make an extend and then assign it, so that part of the original value of the complex object can be retained. For example:



Copy code The code is as follows: var a = {width:120,height: 200};
var c={width:200};
a=c;
a=$.extend(a,c);


The result is first The first a will be {width:20}, which will lose the height:200; while the one below will continue to retain the original height:200.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn