1. Use the hasownproperty () method in for... Loops
Javascript arrays are not associated. You can use them as hash tables and use loops to traverse object attributes:
- For (VAR prop in someobject ){
- Alert (someobject [prop]); // alert's value of property
- }
However, the problem is... in loop traverses attributes of each Enumeration type on the object property chain. If you only want to use attributes actually owned by the object, this may be a problem. How can this problem be solved? You can use the hasownproperty () method. The Code is as follows:
- For (VAR prop in someobject ){
- If (someobject. hasownproperty (PROP )){
- Alert (someobject [prop]); // alert's value of property
- }
- }
2. Event binding
In JavaScript, events are a complex issue. Event bubbling and delegation are replacing inline onclick operations (except for some special "Initial pages ).
Suppose you have an image mesh and you need to start a modal lightbox window. Do not use the following method. The example uses jquery. If you use similar libraries or other libraries, the bubble mechanism is also suitable for traditional JavaScript.
Related HTML code:
- <Div id = "Grid-container">
- <A href = "someimage.jpg"> </a>
- <A href = "someimage.jpg"> </a>
- <A href = "someimage.jpg"> </a>
- ...
- </Div>
Bad JavaScript Syntax:
- $ ('A'). On ('click', function (){
- Calllightbox (this );
- });
This Code assumes that lightbox is called and an anchor element is passed in and the full screen image is referenced. Instead of binding each anchor element, use the # grid-container element directly.
- $ ("# Grid-container"). On ("click", "A", function (event ){
- Calllightbox(event.tar get );
- });
In this Code, thisand event.tar get both represent the anchor element. You can also use it on any parent element. You only need to ensure that the defined element is the event target ).
From above: http://www.csdn.net/article/2012-11-19/2811978-20-All-Too-Common-Coding-Pitfalls-For-Be