October 10, 2005
Version 1.0
Introduction
This document will explain some important Javascript concepts and show the preferred way of handling common situations and problems. It should be read by anyone developing web applications and using javascript.
Square Bracket Notation
Objects properties in javascript can be accessed in two ways: Dot notation and Square bracket notation.
If a property name is being generated at run-time, the bracket notation is required. For example, if you have properties "value1", "value2", and "value3", and want to access the property using a variable i=2:
For convenience and consistency, using square-bracket-notation instead of dot-notation is a good practice to get into.
Referencing Forms And Form Elements
The correct way to reference a form input element is:
All forms should have a name attribute. Referencing forms using indexes, such as document.forms[0] is bad practice.
If you will be referencing multiple form elements within a function, it's best to make a reference to the form object first and store it in a variable.
var theform = document.forms["mainForm"];
theform.elements["input1"].value="a";
theform.elements["input2"].value="b";
Referencing Forms From Element Handlers
When you are validating an input field using onChange or similar event handlers, it is always a good idea to pass a reference to the input element itself into the function. Every input element has a reference to the form object that it is contained in.
<input type="text" name="address" onChange="validate(this)">
function validate(input_obj) {
// Reference another form element in the same form
if (input_obj.form.elements["city"].value=="") {
alert("Error");
}
}
By passing a reference to the form element, and accessing its form property, you can write a function which does not contain a hard reference to any specific form name on the page.
Problems With Concatenation
In javascript, the + operator is used for both addition and concatenation. This can cause problems when adding up form field values, since Javascript is a non-typed language. Form field values will be treated as strings, and if you + them together, javascript will treat it as concatenation instead of addition.
<form name="myform">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
function total() {
var theform = document.forms["myform"];
var total = theform.elements["val1"].value + theform.elements["val2"].value;
alert(total); // This will alert "12", but what you wanted was 3!
}
To fix this problem, Javascript needs a hint to tell it to treat the values as numbers, rather than strings. Subtracting 0 from the value will force javascript to consider the value as a number, and then using the + operator on a number will perform addition, rather than concatenation.
<form name="myform">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
function total() {
var theform = document.forms["myform"];
var total = (theform.elements["val1"].value-0) + theform.elements["val2"].value;
alert(total); // This will alert 3
}
Using onClick in <A> tags
When you want to trigger javascript code from an anchor tag, the onClick handler should be used. The javascript code that runs within the onClick handler needs to return true or false back to the tag itself. If it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onClick handler.
Eval
Detecting Browser Versions
The better approach is to use feature detection. That is, before using any advanced feature that an older browser may not support, check to see if the function or property exists first, then use it. This is better than detecting the browser version specifically, and assuming that you know its capabilities. An in-depth article about this topic can be found at http://www.jibbering.com/faq/faq_notes/not_browser_detect.html if you want to really understand the concepts.
Don't Use document.all
document.all was introduced by Microsoft in IE and is not a standard javascript DOM feature. Although many newer browsers do support it to try to support poorly-written scripts that depend on it, many browsers do not.
There is never a reason to use document.all in javascript except as a fall-back case when other methods are not supported.
if (document.getElementById) {
var obj = document.getElementById("myId");
}else if (document.all) {
var obj = document.all("myId");
}
The rules for using document.all are
- Always try other standard methods first
- Only fall back to using document.all as a last resort
- Only use it if you need IE 5.0 support or earlier
- Always check that it is supported with "if (document.all) { }" around the block where you use it.
Getting And Setting Form Values
The method used to get and set form values depends on the type of form element. A detailed explanation of how to correctly access form controls can be found at http://www.jibbering.com/faq/faq_notes/form_access.html.
In general, it is a good practice to use generalized getInputValue() and setInputValue() functions to read and write values to form elements. This will make sure that it is always done correctly, and situations that otherwise might cause confusion and errors are handled correctly. For example, forms with only 1 radio button in a group, or multiple text inputs with the same name, or multi-select elements.
The getInputValue() and setInputValue() functions are part of the validations.js library from the Javascript Toolbox. The most current version of these functions and other validation functions can be found at http://www.javascripttoolbox.com/validations/.
Additional Resources
The comp.lang.javascript FAQ has many common questions and answers about javascript. It is a great resource to check if you have what you think might be a FAQ.
For general-purpose libraries and examples, see The Javascript Toolbox.
If you want to really exploit the javascript language and use advanced techniques, read about Javascript Closures.
end
相关推荐
JavaScript是Web开发中不可或缺的一部分,它为网页带来了交互性和动态性。在开发过程中遵循最佳实践和技巧,可以提高代码质量,降低维护成本。以下是一些关键的JavaScript最佳实践和技巧: 1. **命名空间和代码结构...
在JavaScript编程中,遵循最佳实践是确保代码可读性、可维护性和性能的关键。以下是一些关于JavaScript的最佳实践和建议: 1. **原型扩展与循环**: JavaScript允许通过原型(prototype)为数据类型添加新功能。...
**JSP(Java Server Pages)** 是一种动态网页技术,它允许开发者在HTML或者XML文档中嵌入Java代码,从而实现...提供的“JSP Examples and Best Practices”PDF文档应包含各种示例和实用建议,有助于读者掌握JSP的精髓。
在这本名为"Best Practices"的章节中,作者可能讨论了如何高效且有效地使用JavaScript与DOM进行交互的一些最佳实践。 在JavaScript DOM编程中,以下是一些关键知识点: 1. **DOM元素选择**:`document....
Over the course of the book, author Frank Zammetti covers JavaScript best practices, Ajax techniques, and some of the most popular JavaScript libraries, such as Prototype, Script.aculo.us, and the ...
Taking a complete journey through the most valuable design patterns in React, this book demonstrates how to apply design patterns and best practices in real-life situations, whether that's for new or ...
• JavaScript——你将获得忠告:理解Ajax性能、编写高效的JavaScript、创建快速响应的应用程序、无阻塞加载脚本等。 • 网络——你将学到:跨域共享资源、无损压缩图片大小,以及使用块编码加快网页渲染。 •...
1. **React基础知识**:React是一个用于构建用户界面的JavaScript库,它强调组件化开发,允许开发者将UI拆分为独立、可复用的部分。在本书的代码中,你可以看到如何创建、组合以及管理React组件,包括使用JSX语法、...
《Ajax Patterns and Best Practices》一书由Christian Gross编写,深入探讨了Ajax模式与最佳实践,为开发者提供了一套系统的方法论,帮助他们更好地理解和应用Ajax技术。 ### Ajax技术概览 Ajax是一种用于创建...
该文件的标题为“EPUB 3 Best Practices”,说明了本文是一份关于EPUB 3开发实践的指南。EPUB 3格式由国际数字出版论坛(IDPF)开发,用于提供一套基于标准的出版物发布系统,它支持诸如富文本格式化、多媒体内容嵌入...
### IBM Redbook - WebSphere Commerce Best Practices in Web 2.0 Store #### 一、引言与概述 《IBM Redbook - WebSphere Commerce Best Practices in Web 2.0 Store》是一份由IBM官方出版的技术指南,主要介绍了...
在`PHP Advanced Ajax Architecture and Best Practices.pdf`中,可能会详细讲解如何创建一个用户登录系统,使用Ajax提交表单,PHP验证用户名和密码,以及在不刷新页面的情况下显示验证结果。这个例子展示了如何将...
### 网站优化资料:Best Practices for Speeding Up Your Web Site #### 一、引言 随着互联网的发展,用户体验成为衡量网站成功与否的重要因素之一。网页加载速度直接影响着用户体验和搜索引擎排名。为了帮助...
- 将模板作为字符串字面量保存在 JavaScript 文件中。 - **预编译模板** - 使用工具如 grunt-template-compile 或 Dust.js 等预编译模板,以提高运行时性能。 - **避免在模板中评估** - 在模板中避免使用复杂的...