Home  >  Article  >  Web Front-end  >  Five things to note when developing JavaScript_javascript tips

Five things to note when developing JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 19:07:25970browse
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, and Do not bind 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 for accessibility. Problems can be solved through 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 code The code is as follows:

for ( var i = 0, j = elements.length; i < j; i )

This way you can store the number of elements (the value of elements.length) In a variable j, this eliminates the 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 is 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, all Put strings and variables into an array, and then use the join method to form 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