大多數開發人員選擇用單引號,因為XTHML要求所有XHTML的屬性都必須使用雙引號
var html='<h2 class="a">A list!</h2>' +'<ol>' +'<li class="a">Foo</li>' +'<li class="a">Bar</li>' +'</ol>'
總是比
var html="<h2 class=\"a\">A list!</h2>" +"<ol>" +"<li class=\"a\">Foo</li>" +"<li class=\"a\">Bar</li>" +"</ol>"
但是對於行內(inline)單引號仍然必須轉義:
var html = '<p class="a">Don\'t forget to escape single quotes!</p>';
最佳方案就是使用串連操作符(+)並將每行用引號括起來:
var html='<h2 class="a">A list!</h2>' +'<ol>' +'<li class="a">Foo</li>' +'<li class="a">Bar</li>' +'</ol>'
相同名字的函數永遠只能存在一個執行個體。如果編寫如下的函數
function alert(message){ ADS.$('messageBox').appendChild(document.createTextNode(message));}
瀏覽器將不會執行往常的提示資訊
看一下我們常規的註冊函數
function clicked(){ alert('Linked to :'+this.href);}var anchor= ADS.$('someID');ADS.addEvent(anchor,'click',clicked)
匿名函數:
var anchor=ADS.$('someId');addEvent(anchor,'click',function(){ alert('Linked to:' + this.href);});
範圍:(通過var維護範圍鏈)
function myFunction(){ var myVar='inside';}//定義變數var myVar='outside';myFunction();alert(myVar);//outside
如果去掉:
function myFunction(){ myVar='inside';}//定義變數var myVar='outside';myFunction();alert(myVar);//inside
下面看一個例子:
ADS.addEvent(window, 'load', function(W3CEvent) { for (var i=1 ; i<=3 ; i++ ) { var anchor = document.getElementById('anchor' + i); ADS.addEvent(anchor,'click',function() { alert('My id is anchor' + i); }); }});
View Code
<ul> <li><a href="http://advanceddomscripting.com" id="anchor1">Anchor 1</a></li> <li><a href="http://advanceddomscripting.com" id="anchor2">Anchor 2</a></li> <li><a href="http://advanceddomscripting.com" id="anchor3">Anchor 3</a></li></ul>
View Code
目的:點擊anchorx 便提示My id is anchorx,但是情況卻不是這樣。
原因:i的值時間上是在單機時間發生時,才從 範圍鏈中取得的,當單機時間發生時,initAnchors()已經執行完畢,因此i的值為4,所以每個alert()顯示的都是同一個結果。原因:
處理辦法:
function registerListener(anchor,i) { ADS.addEvent(anchor, 'click', function() { alert('My id is anchor' + i); });}function initAnchors() { for ( i=1 ; i<=5 ; i++ ) { var anchor = document.getElementById('anchor'+i); registerListener(anchor,i); }}ADS.addEvent(window, 'load', initAnchors);
通過hasOwnProperty()方法檢查不涉及其他對象繼承的屬性和方法。智慧檢查在特定對象自身中直接建立的屬性
var all=document.body.getElementsByTagName('*');for(i in all){ if (!all.hasOwnProperty(i)) { continue; } //對all[i]元素進行某些操作}
//賦一個函數傳回值var foo = exampleFunction();//賦一個函數的引用var foo = exampleFunction;
View Code