Home  >  Article  >  Web Front-end  >  Five practical tips in JavaScript programming development_javascript skills

Five practical tips in JavaScript programming development_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:22:401182browse

Really five quick tips:

Only use the submit event on the

element
If you want to bind an event handler in the form, you should only use it on the Bind the submit event to the element instead of binding the click event to the submit button.
March: This method is certainly good, but the company used Web Flow during development. One page is a large form, and there may be several submit buttons in it, so some event handlers have to be bound to the submit button. On the click event of the button.

All clickable items should be links
Do not bind click events to elements other than anchor elements (). This is important for keyboard users, who can have difficulty getting focus on an element via the keyboard alone.
March: However, I personally feel that anchor elements should only be used as links, and some functional operations (such as Google Reader's Mark all as new) are best marked with . Accessibility issues can be solved through Solved by shortcut keys and other methods. This can better restore the semantics of HTML elements.

Simple for loop optimization
When you write a for loop, there is a very simple trick that can improve performance.

Copy code The code is as follows:
for ( var i = 0; i < elements.length; i )

Use the following statement instead of the above:
Copy the code The code is as follows:
for (var i = 0, j = elements.length; i < j; i )

This way, the number of elements (the value of elements.length) can be stored in a variable j, so there is no need to Count the number of elements each time through the loop.

Use anonymous functions as event handlers
Especially for short functions, creating an anonymous function can be more readable than using a reference to a named function.
Copy code The code is as follows:
anchor.onclick = function() { map.goToPosition( home ); return false; }

March: It is more efficient to use named functions when developing more complex JavaScript.

Use Array.join instead of concatenating strings
When concatenating many strings, variables, etc. into a long string, combine all strings and Put the variables into an array, and then use the join method to form them into a long string, which is better than string concatenation in terms of code readability and performance.
Copy code The code is as follows:

var text = 'There are' elements.length 'members in the elements array.';
var text = ['There are', elements.length, 'members in the elements array.'].join(' ');
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