主题:16    

2006/05/10

Prototype 文档

Prototype: http://prototype.conio.net/

是一个比较有名的 web2.0 (Ajax) 时代 Javascript  lib 库,但其缺乏一定的文档,使得使用起来比较困难。

这里有不少人通过自己查看源代码,撰写了第三方的文档,

英文的:http://www.sergiopereira.com/articles/prototype.js.html

中文的:https://compdoc2cn.dev.java.net/prototype/html/prototype.js.cn.html

阿涂 发表于 2006-05-10 11:17   阅读( 1269) 评论( 0) 引用( 5) javascript

2006/04/30

比较有用的 firefox 插件 firebug

http://www.joehewitt.com/software/firebug/

阿涂 发表于 2006-04-30 15:46   阅读( 1390) 评论( 3) 引用( 0) javascript

2006/04/21

Web 2.0 Mashup Matrix

http://www.programmableweb.com/matrix

阿涂 发表于 2006-04-21 18:32   阅读( 766) 评论( 0) 引用( 0) javascript

a good web design site

http://www.webdesignfromscratch.com/

阿涂 发表于 2006-04-21 18:31   阅读( 652) 评论( 0) 引用( 0) javascript

UnobtrusiveJavascript-(创建删除内容)

Dom 强大之处在于不仅仅可以支持遍历节点,它还可以动态的创建和删除节点。

创建新的对象:

createElement(element)
Creates a new element
createTextNode(string)
Creates a new text node with the value string.
Newly created elements are not added to the document immediately, they remain in limbo until we append them somewhere in the node tree. These functions have to be applied to the document object rather than to a node.

需要注意的是,新创建的节点在我们append或者insert到document对象前是不会直接包含在 document 中。

修改现有对象

setAttribute(attribute,value)
Adds a new attribute with the value to the object
appendChild(child)
Adds child as a childNode to the object. child needs to be an object, you cannot use a string.
cloneNode()
Copies the whole node with all childNodes.
hasChildNodes()
Checks if an object has childNodes, and returns true if that is the case.
insertBefore(newchild,oldchild)
Adds newchild before oldchild to the document tree.
removeChild(oldchild)
Removes the childnode oldchild.
replaceChild(newchild,oldchild)
Replaces oldchild with newchild.
removeAttribute(attribute)
Removes the attribute from the object.

 这里还有作者总结的一些编写相关代码的一些原则(或者小结)

1、访问一个对象前先判断是否为NULL

2、不要太过于依赖标记(html tag),这样当 <html> 修改是不会让你频繁修改 javascript

3、使用document.getElementsByTagName('h2')[0].firstChild.nodeValue 访问一个元素的内容,而不是使用document.getElementsByTagName('h2')[0].nodeValue

4、nodeName 和 attributes 要大小写不区分

5、Dom 产生的html代码是没有经过很好的格式化的,(就是没有排版过得,比如缩进),因此要产生可以公用的 html 代码,还是需要手写的。

6、避免过多的循环,比如使用ID代替class来查找一个对象就可以避免过多的循环

7、Know your syntax. Many a time a getElementsById can cause a lot of rescripting

8、Know your Javascript objects and HTML attributes, it is no use checking for an attribute that is not meant to be there to start with.

9、Don't assume your own ways of marking up to be commonly used. An example is to check if the className contains your string rather than is your string, as some developers like using multiple classes.

这三条还没有理解,不知道如何翻译 :)

9、关于 innerHTML , 在需要对创建的对象还要做一系列操作或者修改时,不要使用 innerHTML , innerHTML 可以快速创建大量的 html 文本,但它仅仅是产生文本,并不能帮你获得相关的对象引用。

What about innerHTML?

When Internet Explorer 4 came to be, innerHTML was born, a fast way to generate and change content. It is a way to read the content of an element a lot easier than with the original W3C recommendations. This is especially the case, if an element contains childNodes which are elements themselves and we want to read the whole content. To do this with DOM only, you need to go through excrutiating exercises[1] of checking nodeTypes and reading the values of each child node. innerHTML is a lot easier to use, but has some drawbacks. For example you do not get any references back to the elements you create with it as the whole value is a string rather than objects. Furthermore, innerHTML is only HTML related, not XML, and DOM was meant to traverse any markup. For a comparison and browser support check the DOM section of Quirksmode.org[2] or the big discussion at Developer-x[3].

 

两个相关的示例演示:

The picture example

Let's say we have links to images, and they should open in a new window in browsers without Javascript, or below the links when Javascript is available.

	HTML:<ul id="imglist"> <li><a href="home.gif" target="_blank">Home  (new window)</a></li> <li><a href="home_on.gif" target="_blank">Home active  (new window)</a></li> <li><a href="jscsshtml.gif" target="_blank">HTML-CSS-Javascript  (new window)</a></li></ul>
	

Now, when Javascript and DOM is available, we want to:

  • Get rid of the "(new window)" wording in the links.
  • Add an event handler to call a function popw()

This function should

  • Show the linked image below the link when it is not there already.
  • Remove the image, if it is already there (to avoid the link to add the image over and over again).
  • Make the image disappear when users click on it.

The first problem is not hard to solve:

	Javascript:function imgpop(){ var il,imga,imgatxt;// get all LIs in imagelist, loop over them  il=document.getElementById('imglist').getElementsByTagName('li'); for(i=0;i<il.length;i++) {// grab first link in the LI imga=il[i].getElementsByTagName('a')[0];// delete the wording (new window) in the link text // (which is the nodeValue of the first node)   imgatxt=imga.firstChild; imgatxt.nodeValue=imgatxt.nodeValue.replace(/ \(new window\)/,'');// add the event handlers to call popw(); imga.onclick=function(){return popw(this);} //imga.onkeypress=function(){return popw(this);} }}
	

Now, for the function popw() we need to use some of the methods shown above:

	Javascript:function popw(o){ var newimg;// if there is already an image in the parentNode (li)  if(o.parentNode.getElementsByTagName('img').length>0) {// delete it  o.parentNode.removeChild(o.parentNode.getElementsByTagName('img')[0]); } else {// else, create a new image and add a handler that removes it when you // click it  newimg=document.createElement('img');  newimg.style.display='block';  newimg.onclick=function(){this.parentNode.removeChild(this);};  newimg.src=o.href;  o.parentNode.appendChild(newimg) } return false;}See this imagepop example in action
	

The datepicker link example

Let's say for example we have a form that has date fields and we want to offer users with Javascript enabled a date picker, others should simply enter the date by hand. Let's not discuss the date picker function now, but focus on how to call it.

We start with the necessary HTML. To see which element should get a datepicker link, we add classes with the name date to them.

	HTML:<h1>Flight booking</h1><form action="nosend.php" method="post" script_onsubmit="return check(this);"><p>Step 1 of 4</p><h2>Please select your dates</h2><p> <label for="startdate">Start Date</label> <input type="text" class="date" id="startdate" name="startdate" /></p><p> <label for="enddate34;>End Date</label> <input type="text" class="date" id="enddate" name="enddate" /></p><p> <input type="submit" value="send" /></p></form>
	

We loop through all inputs in the document, and check which one has a className that contains date (remember, elements can have more than one class in the class attribute!).

If that is the case, we create a new link, and a link text. We append the link text as a child of the link and add event handlers to call our picker script.

Once the link is created, we append it after the input field.

	Javascript:function addPickerLink(){ var inputs,pickLink,pickText;// loop through all inputs inputs=document.getElementsByTagName('input'); for(i=0;i<inputs.length;i++) {  // if the class contains 'date'  if(/date/.test(inputs[i].className))  {// create a new link and a text   pickLink=document.createElement('a');   pickText=document.createTextNode('pick a date');// add the text as a child of the link   pickLink.appendChild(pickText);// set the href to # and call picker when clicked or tabbed to     pickLink.setAttribute('href','#');   pickLink.onclick=function(){picker(this);return false;};   //pickLink.onkeypress=function(){picker(this);return false;};// add the new link to the parent of the input field (the P)   inputs[i].parentNode.appendChild(pickLink)  } }}See the picker demo in action.
	

Now all fields with dates have a link after them that links to picker().

All we need now is to tell the picker function where to apply the return value to.

As we send the link itself as the object to picker(), we need to access its previous sibling, the INPUT.

	Javascript:function picker(o){ alert('This is a simulation only.') // no real function today o.previousSibling.value='26/04/1975';		}
	

Close, but not quite. As we appended the new link as the last child to the parent node of the input, it could very well be that the previousSibling of our new link is indeed not the INPUT but whitespace! Therefore, we need to loop through the previous siblings until we hit an element.

	Javascript:function picker(o){ alert('This is a simulation only.') // no real function today while(o.previousSibling.nodeType!=1) {  o=o.previousSibling; } o.previousSibling.value='26/04/1975';		}
	

Looping is always hacky and could be rather slow. To avoid the loop we have to change our function.

Changing the addPickerLink() function

It is always easy to use appendChild(), but it makes us dependent on the markup. What happens for example if we need to add a SPAN with an asterisk next to the input to indicate a mandatory field later on?

The trick is use insertBefore() on the nextSibling of our input field.

	Javascript:function addPickerLink(){ var inputs,pickLink,pickText;// loop through all inputs inputs=document.getElementsByTagName('input'); for(i=0;i<inputs.length;i++) {		// if the class contains 'date'   if(/date/.test(inputs[i].className))   {// create a new link and a text    pickLink=document.createElement('a');    pickText=document.createTextNode('pick a date');	// add the text as a child of the link    pickLink.appendChild(pickText);// set the href to # and call picker when clicked or tabbed to		    pickLink.setAttribute('href','#');     pickLink.onclick=function(){picker(this)};    //pickLink.onkeypress=function(){picker(this)};// add the new link directly after the input    inputs[i].parentNode.appendChild(pickLink)    inputs[i].parentNode.insertBefore(pickLink,inputs[i].nextSibling);    }  }}See the cleaner picker demo in action.
	

 

 

阿涂 发表于 2006-04-21 10:06   阅读( 648) 评论( 0) 引用( 0) javascript

Unobtrusive Javascript(如何改变)

该系列文章的第二章,主要描述的是我们可以通过一系列的改变,达到写出不唐突的javascript代码。

基本大意是所有写在 xhtml 中的 CSS 以及 javascript ,基本都通过 Dom 对象树的遍历找到相应的对象,然后通过对该对象的事件以及样式属性的修改,达到改变它的显示以及行为。

在原始 xhtml 代码中,只需要定义相应的 class 或者 id 就可以了; 这样有利于操作型或者样式型的代码和页面内容分离。

另外文中还演示了关于rollover的典型使用方法, 感兴趣的可以仔细阅读一下,原文网址:

http://www.onlinetools.org/articles/unobtrusivejavascript/chapter2.html, 摘录如下:

 

For the inexperienced Javascript developers, HTML is their playground.

		HTML:home 	
	

or if they are a bit more advanced:

		HTML:home Javascript:// preloading imagehomeoff = new Image(); homeoff.src = 'home.gif';homeon = new Image(); homeon.src = 'homeoff.gif';function roll(imgName,a) { imgState=a==0?eval(imgName + 'on.src'):eval(imgName + 'off.src'); document.images[imgName].src = imgState;}	
	

In any case, all the event calls are in the HTML, and if the function name changes, we'd have to change each document. Furthermore, each rollover means a lot of markup which adds to the overall page weight.

Out! Out! - you demons of inline event calls

Let's forget for the moment, that almost every rollover effect these days can be achieved via CSS rather than Javascript - let's say we want to use the following markup and create a rollover for the image:

		HTML:home	
	

Now, how to change that when the mouse is over it?

Climbing the branches of the node tree

Each XML (and that includes HTML) document is a node tree. A node is a part of this tree (think of a file or a folder in windows explorer when you navigate around your harddisk). A node can be twelve different things[1] - for HTML, only three are really interesting: element, TextNode and AttributeNode.

Our climbing equipment

Let's see which functions and attributes we can use to navigate the node tree of a document, and how to jump from one element to another.

Functions to reach an element in the page

getElementById('elementID')
returns the element with the id elementID as an object.
getElementsByTagName('tag')
returns all elements with the name tag as an array.

Of course you can mix and match these two. Some examples:

		document.getElementById('navigation').getElementsByTagName('a')[3];	returns the fourth link inside the element with the ID 'navigation'document.getElementsByTagName('div')[2].getElementsByTagName('p')[0];	returns the first paragraph inside the third div in the document.	
	

Tools to navigate from a certain element

childNodes
returns an array of all the nodes inside the current one. There is also firstChild and lastChild, which are shorter versions for childNodes[0] and childNodes[this.childNodes.length-1].
parentNode
The element containing this one
nextSibling
the next element on the same level in the document tree
previousSibling
the previous element on the same level in the document tree

All of these can be mixed at will and need.

		Javascript:var other=document.getElementById('nav').childNodes[3].firstChild;	returns the 4th element's first sub element inside the element 	with the ID nav.var prevlink=o.parentNode.previousSibling.firstChild.childnodes[2];	returns the third node inside the previous element 	that is on the same level as the parent element of o.	
	

Attributes and functions for elements

attributes
returns an array of all the attributes of this element. Does not work with Internet Explorer below version 6.
data
returns or sets the textual data of the node
nodeName
returns the name of the node (the HTML element name)
nodeType
returns the type of the node — 1 is an element node, 2 attribute and 3 text.
nodeValue
returns or sets the value of the node. This value is the text when the node is a textnode, the attribute if it is an attribute or null if it is an element.
getAttribute(attribute)
returns the value of the attribute attribute.
		Javascript:var other=document.getElementById('nav').firstChild;if(other.nodeType==3){ other.data='newtext';} if(other.nodeType==1){ other.firstChild.data='newtext';} 	
	

Now to reach the image in our example, we can use either getElementsByTagName or getElementById.

		HTML:homeJavascript:function findimg(){ var image; image=document.getElementById('home'); if (image)   {   image.style.border='3px dashed #ccc';  }}or:function findimg(){ var imgs,i; imgs=document.getElementsByTagName('img'); for(i in imgs) {  if(/home.gif/.test(imgs[i].src))   {    imgs[i].style.border='3px dashed #ccc';   }  }}	
	

Using getElementById is a lot easier, as we don't have to loop through all elements and find a unique identifier. In this example, we checked if the src attribute of the image object contains 'home.gif'. A more common way is to check for a special class.

		HTML:homeJavascript:function findimg(){ var imgs,i; imgs=document.getElementsByTagName('img'); for(i in imgs)  {  if(/roll/.test(imgs[i].className))   {    imgs[i].style.border='3px dashed #ccc';   }  }}	
	

Now, to add a roll-over effect, all we need to do is to add a function that does the switching of the image source, and adds the event handlers to the image.

		function findimg(){ var imgs,i;// loop through all images of the document imgs=document.getElementsByTagName('img'); for(i=0;iTest this example here.	
	

Good for the moment, but we forgot one thing: Albeit being merely eye candy, a rollover should work without a mouse, too. To achieve this, we need to check if the link around the image gets the focus or not, as the image itself is not reachable via the keyboard when embedded in a link.

To do this, we need to get the element that contains the image, in this case the link. We do this via parentNode command. As this also changes the object that gets sent as a parameter to the function roll(), we need to find the image again. Hence we loop through the childNodes of the link and check which one is an element and an image by checking nodeType and nodeName. This is necessary, as some browsers see whitespace in the source as an own node, whereas others don't.

		function findimg(){ var imgs,i;// Loop through all images, check if they contain the class roll imgs=document.getElementsByTagName('img'); for(i=0;iTest this mouse independent example here.	
	

Why don't you try it?

Simply download the demo HTML and try one of the following tasks. Follow the solution links to see one possible solution. The solutions have the Javascript inline as a demonstration, not in an extra document where they should be. This was done to help you see the necessary markup in one document rather than two.

  1. Change the colour of every H2 headline to blue. Solution colourchange.
  2. Outline every second paragraph with a black border. Solution p-border.
  3. Check which of the links in the document is external (by checking that the href attribute does not contain window.location.hostname) and add the href of the link as a text in parenthesis after the link. Until you learn how to do that propely, use the innerHTML attribute of the link object to change its content. Solution external links.
  4. Add an script_onclick handler to each link with the attribute target that opens a 400x400 pixels pop-up window. Solution pop-up.

Links

阿涂 发表于 2006-04-21 09:41   阅读( 651) 评论( 0) 引用( 0) javascript

Unobtrusive Javascript - (清除操作代码)

原文为:Operation Cleanout in process

即将原来大家在 xhtml ,中写的大量关于操作行为的 Javascript 代码以及样式控制的 CSS 清除, 文中指出了一些常见的清除行为:

1、使用样式继承取代许多写在xhtml中的代码:

	HTML:<table border="0" cellpadding="0" width="100%" cellspacing="5"><tr> <td><font face="Arial" size="-2">Lorem Ipsum</font></td></tr></table>
	

became

	CSS:td.content {font-family:Arial,sans-serif;font-size:12px;}HTML:<table cellpadding="0" style="width:100%;border:none" cellspacing="5"><tr> <td class="content">Lorem Ipsum</td></tr></table>
	

and finally

	CSS:body {font-family:Arial,sans-serif;font-size:12px;}p {padding:5px;}HTML:<p>Lorem Ipsum</p>
	

2、保持javascript独立

2。1 使用独立的 javascript 文件,即不要在xhtml 中出现任何javascript代码

1. Never, under any circumstances add Javascript directly to the document.

One of the big powers of Javascript is that it comes in a seperate file. Much like CSS, this means you can apply one collection of functions to every page of the site, and if you need to change its functionality, you can do that in one document rather than going through each page.

This means - unless there are special circumstances - all we ever need to see in an HTML document is:

	<script type="text/javascript" src="scripts.js"></script>
	

2。2 Javascript 只是一种增强, 并不是一种安全的方法, 因此需要让你的网页可以独立于javascript运行

 

We only use Javascript to enhance a functionality that is already given, we don't rely on it. Javascript can be turned off or filtered out by proxies or firewalls of security aware companies. We can never take it for granted.

This does not mean we cannot use Javascript, it only means we add it as an option rather than a requirement.

	HTML:<form action="index.php" script_onsubmit="return checkform(this)"> <p><label for="login">Login:</label> <input type="text" name="login" id="login" /></p> <p><label for="pw">Password:</label> <input type="password" name="pw" id="pw" /></p> <p><input type="submit" value="send" /></p></form>Javascript:function checkform(f){ var error=''; error+=f.login.value==''?'\nlogin':''; error+=f.pw.value==''?'\npassword':''; if (error!='') {  alert('Please enter the following:'+error); }  return error=='';}
	

Is perfectly valid, and will prevent the users from experiencing a reload when they forgot to enter a value.

	HTML:<form action="index.php"> <p><label for="login">Login:</label> <input type="text" name="login" id="login" /></p> <p><label for="pw">Password:</label> <input type="password" name="pw" id="pw" /></p> <p><input type="button" script_onclick="checkform()" value="send" /></p></form>Javascript:function checkform(){ var f=document.forms[0]; var error=''; error+=f.login.value==''?'\nlogin':''; error+=f.pw.value==''?'\npassword':''; if (error!='') {  alert('Please enter the following:'+error); } else {  f.submit(); }}
	

Seemingly does the same, but has one problem: If Javascript is turned off, the button does nothing whatsoever, no matter how often the frustrated user clicks it. Let's repeat: Javascript is not to be trusted, let's not rely on it!

2。3 在使用一个javascript对象前一定要检查变量是否可用

 

A lot of Javascript errors are occuring simply because the scripter was too lazy to check if a method or an object is available or not.

	Javascript:function color(o,col){ o.style.background=col;	}
	

could result in a Javascript error, when the object o is not available.

	Javascript:function color(o,col){ if(o) {  o.style.background=col; }	}
	

works all the time.

This technique is mainly used to check if a browser is able to support a certain Javascript functionality. Back in the days of trial and error while developing (it didn't matter, the clients paid, or the .COM we worked for) this was achieved via a browser-sniffing script, an ill-fated concept from the start (every time a browser was updated or a new one came around, the sniffer script needed updating). For most of the examples used nowadays it is necessary to check if the browser is able to understand the W3C[1] DOM[2], which brings us to the next rule.

2。4 不要创建任何和浏览器相关的javascript代码

比如 document.layer 是netscape专有的,而document.all是IE专有的方式,但 document.getElementById 是目前所有浏览器都支持的方式

 

Unless there is a really good reason, we should never use browser specific extensions to the web standards. The times of checking for document.layers (Netscape 4.x) or document.all (Internet Explorer < 5) are over. Modern browsers all support the document.getElementsById DOM, and that's what we use and test for.

	Javascript:function doDOMstuff(){ if(document.getElementById && document.createTextNode) {  [...] }}
	

The second check is only necessary as some earlier versions of Opera claimed to understand the DOM, but failed to do so properly.

2。5 不要覆盖其他变量,尽量使用本地变量

 

When we create a function or functionality we should make sure that all the variables used are local, to avoid one function overwriting a variable that is in use by another.

	Javascript:var i=42; // global variablefunction dothings(){ for (i=0;i<200;i++) // i gets changed {  // some code  }}function dothingsright(){ var i; // define i locally for (i=0;i<200;i++) {  // some code  }}alert(i); // = 42dothingsright()alert(i) // = 42 (due to local definition)dothings()alert(i) // = 200, oops!
	

2。6 使鼠标的应用独立,即用户即使不使用鼠标也可以正常访问你的网页。

 

Just making sure that things only work when Javascript is enabled is not enough. We also have to be aware of users who cannot use a mouse at all or only badly. Therefore we must ensure that all effects are triggered by mouse and by keyboard access.

The biggest problem with mouse independence are form elements that get validated or trigger an effect onchange or onblur. Don't use them, it is as simple as that.

A common use of this inaccessible technique is select boxes as navigations.

	HTML:<form><p><label for="go2">Go to:</label><select name="go2" id="go2" script_onchange="send(this)"> <option value="index.html">Home</option> <option value="chapter1.html">Operation Cleanout</option> <option value="chapter2.html">Reaching things</option></select></p></form>Javascript:function send(f){ var chosen; chosen=f.options[f.selectedIndex].value; self.location=chosen;}    Test this inaccessible selectbox example.
	

Seemingly the main problem is that when you use a keyboard to tab to the element and hit arrow down to select something you can never get past the first option, as send() gets triggered when you go from the first to the second option.

Experienced keyboard users will know though that you have to hit alt+arrow down first to expand the whole drop-down before choosing.

However, this is not known to all users. Furthermore, the example does nothing when Javascript is not available.

	HTML:<form action="send.php" method="post" script_onsubmit="return send(this)"><p><label for="go2">Go to:</label><select name="go2" id="go2"> <option value="index.html">Home</option> <option value="chapter1.html">Operation Cleanout</option> <option value="chapter2.html">Reaching things</option></select><input type="submit" value="go" /></p></form>Javascript:function send(f){ var chosen; chosen=f.go2.options[f.go2.selectedIndex].value; self.location=chosen; return false;}    PHP:<?PHP if(isset($_POST['go2'])){ header('Location:'.$_POST['go2']);}?>Test this accessible selectbox example.
	

This, in comparison, works fine, and saves us one server hit to the redirect script send.php, which gets accessed only when Javascript is not available.

What about the onkeypress?

When we read through the Web Content Accessibility Guidelines[3], we are asked to use device independent event handlers for our scripts:

Otherwise, if you must use device-dependent attributes, provide redundant input mechanisms (i.e., specify two handlers for the same element): Use "onmousedown" with "onkeydown". Use "onmouseup" with "onkeyup" Use "onclick" with "onkeypress"

This sounds perfect in theory, but in real life situations, the script_onkeypress handler is badly supported in different browsers. Users that are dependent on keyboard browsing do normally have a key set up to simulate clicking, either the enter key or space bar, and both of these do fire the onclick event. By using onkeypress we might hijack other keyboard functionality the user wants. Examples are the type ahead functionality[4] of Mozilla, Opera's extensive keyboard shortcuts[5] (like 'A' for next link) or JAWS' keyboard controls[6].

So by doing the right thing according to the accessibility guidelines, we might make our script even less accessible.

In the examples to follow in this course, we will add onkeypress as extra handlers, but keep them commented out. This is done to be able to enable these should the necessity occur, or if you have to pass an accessibility audit testing with automated tools rather than real people.

参考资源:

Links

 

 

阿涂 发表于 2006-04-21 09:27   阅读( 942) 评论( 2) 引用( 0) javascript

Unobtrusive Javascript(不唐突的Javascript)

Javascript is a wonderful tool to enhance the usability of web sites. It is the extra layer above the mark-up "what is this text" and the CSS "how should it be displayed". Javascript adds a new dimension, the "how should this element behave".

最近比较流行的一种关于javascript 编程的一些习惯,即:

xhtml 代表文本

CSS 代表样式

Javascript 代表行为

基于这样一种编程方式,称为 Unobtrusive Javascript ,又一个新名词。

下面是这篇文章的 url , 有兴趣的可以去读一下。

http://www.onlinetools.org/articles/unobtrusivejavascript/

 

阿涂 发表于 2006-04-21 09:23   阅读( 481) 评论( 0) 引用( 0) javascript

2006/04/20

代码片断"Unobtrusive JavaScript" Tree Control (收藏)

Here's a tree control that uses semantic HTML, unobtrusive JavaScript, and is easily reusable in a bundle of applications.

Here's the first of what will hopefully be a bunch of code that we donate to the web at large. I made this a few months ago, but it's been serving me well.

There are a lot of tree controls out there, but most of them are tacky, heavyweight relics of the"DHTML" era. I felt it was time for a change. In particular, I wanted to adopt "unobtrusive javascript" techniques. Among other things, the script has these notable features:

  • All of the styling is in a seperate CSS file. The only thing that the JavaScript manipulates is class names. This gives you a lot of control over the design relatively easily.
  • There is a no "set up code". The script searches for
      and applies its magic to that.
    • All of the content as loaded in a set of nested
        s - the simplest, code that I could think of that was semantically linked to heirachical data.

      http://www.silverstripe.com/downloads/tree/ has a demo, instructions, and a bit of information about how I put it together.

      Or you can just download it here. It's 10kb, including images, CSS, JavaScript and documentation.

阿涂 发表于 2006-04-20 18:46   阅读( 429) 评论( 0) 引用( 0) javascript

2006/03/13

(ZT)The World's Most Misunderstood Programming Language

http://www.crockford.com/javascript/javascript.html

JavaScript:
The World's Most Misunderstood Programming Language

 

Douglas Crockford
www.crockford.com

 

JavaScript, aka Mocha, aka LiveScript, aka JScript, aka ECMAScript, is one of the world's most popular programming languages. Virtually every personal computer in the world has at least one JavaScript interpreter installed on it and in active use. JavaScript's popularity is due entirely to its role as the scripting language of the WWW.

Despite its popularity, few know that JavaScript is a very nice dynamic object-oriented general-purpose programming language. How can this be a secret? Why is this language so misunderstood?

The Name

The Java- prefix suggests that JavaScript is somehow related to Java, that it is a subset or less capable version of Java. It seems that the name was intentionally selected to create confusion, and from confusion comes misunderstanding. JavaScript is not interpreted Java. Java is interpreted Java. JavaScript is a different language.

JavaScript has a syntactic similarity to Java, much as Java has to C. But it is no more a subset of Java than Java is a subset of C. It is better than Java in the applications that Java (fka Oak) was originally intended for.

JavaScript was not developed at Sun Microsystems, the home of Java. JavaScript was developed at Netscape. It was originally called LiveScript, but that name wasn't confusing enough.

The -Script suffix suggests that it is not a real programming language, that a scripting language is less than a programming language. But it is really a matter of specialization. Compared to C, JavaScript trades performance for expressive power and dynamism.

Lisp in C's Clothing

JavaScript's C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java. It has arrays instead of lists and objects instead of property lists. Functions are first class. It has closures. You get lambdas without having to balance all those parens.

Typecasting

JavaScript was designed to run in Netscape Navigator. Its success there led to it becoming standard equipment in virtually all web browsers. This has resulted in typecasting. JavaScript is the George Reeves of programming languages. JavaScript is well suited to a large class of non-Web-related applications

Moving Target

The first versions of JavaScript were quite weak. They lacked exception handling, inner functions, and inheritance. In its present form, it is now a complete object-oriented programming language. But many opinions of the language are based on its immature forms.

The ECMA committee that has stewardship over the language is developing extensions which, while well intentioned, will aggravate one of the language's biggest problems: There are already too many versions. This creates confusion.

Design Errors

No programming language is perfect. JavaScript has its share of design errors, such as the overloading of + to mean both addition and concatenation with type coercion, and the error-prone with statement should be avoided. The reserved word policies are much too strict. Semicolon insertion was a huge mistake, as was the notation for literal regular expressions. These mistakes have led to programming errors, and called the design of the language as a whole into question. Fortunately, many of these problems can be mitigated with a good lint program.

The design of the language on the whole is quite sound. Surprisingly, the ECMAScript committee does not appear to be interested in correcting these problems. Perhaps they are more interested in making new ones.

Lousy Implementations

Some of the earlier implementations of JavaScript were quite buggy. This reflected badly on the language. Compounding that, those implementations were embedded in horribly buggy web browsers.

Bad Books

Nearly all of the books about JavaScript are quite awful. They contain errors, poor examples, and promote bad practices. Important features of the language are often explained poorly, or left out entirely. I have reviewed dozens of JavaScript books, and I can only recommend two: JavaScript: The Definitive Guide (4th Edition) by David Flanagan and Dynamic HTML (2nd Edition) by Danny Goodman. Both are from O'Reilly.

Substandard Standard

The official specification for the language is published by ECMA. The specification is of extremely poor quality. It is difficult to read and very difficult to understand. This has been a contributor to the Bad Book problem because authors have been unable to use the standard document to improve their own understanding of the language. ECMA and the TC39 committee should be deeply embarrassed.

Amateurs

Most of the people writing in JavaScript are not programmers. They lack the training and discipline to write good programs. JavaScript has so much expressive power that they are able to do useful things in it, anyway. This has given JavaScript a reputation of being strictly for the amateurs, that it is not suitable for professional programming. This is simply not the case.

Object-Oriented

Is JavaScript object-oriented? It has objects which can contain data and methods that act upon that data. Objects can contain other objects. It does not have classes, but it does have constructors which do what classes do, including acting as containers for class variables and methods. It does not have class-oriented inheritance, but it does have prototype-oriented inheritance.

The two main ways of building up object systems are by inheritance (is-a) and by aggregation (has-a). JavaScript does both, but its dynamic nature allows it to excel at aggregation.

Some argue that JavaScript is not truly object oriented because it does not provide information hiding. That is, objects cannot have private variables and private methods: All members are public.

But it turns out that JavaScript objects can have private variables and private methods. (Click here now to find out how.) Of course, few understand this because JavaScript is the world's most misunderstood programming language.

Some argue that JavaScript is not truly object oriented because it does not provide inheritance. But it turns out that JavaScript supports not only classical inheritance, but other code reuse patterns as well.

Copyright 2001 Douglas Crockford. All Rights Reserved Wrrrldwide.

 

阿涂 发表于 2006-03-13 23:04   阅读( 813) 评论( 0) 引用( 0) javascript

您的浏览器可能不支持Frame, 优友地带需要使用Frame才能显示正常页面!