Home > Web Front-end > JS Tutorial > Five tips for JavaScript development

Five tips for JavaScript development

黄舟
Release: 2016-12-14 15:44:50
Original
884 people have browsed it

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 bind the submit event on 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 click event.

Everything that is clickable should be links

Do not bind click events to elements other than anchor elements (). This is important for keyboard users, as they can have difficulty getting focus on an element through 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 shortcut keys. Solved by 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.
for ( var i = 0; i < elements.length; ++i )
Use the following statement instead of the above:
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 that there is no need to calculate the number of elements every time it loops.

Use anonymous functions as event handlers

Especially for short functions, creating an anonymous function will be more readable than using a reference to a named function.
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, put all the strings and variables into an array, and then use the join method to They form a long string, which is better than string concatenation in terms of code readability and performance.
var text = 'There are' + elements.length + 'members in the elements array.';
var text = ['There are', elements.length, 'members in the elements array.'].join(' ' );

For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template