內(nèi)容導(dǎo)讀: 有了 With 語句,在存取對(duì)象屬性和方法時(shí)就不用重復(fù)指定參考對(duì)象,在 With 語句塊中,凡是 JavaScript 不識(shí)別的屬性和方法都和該語句塊指定的對(duì)象有關(guān)。With 語句的語法格式如下所示:
With Object {Statements}對(duì)象指明了當(dāng)語句組中對(duì)象缺省時(shí)的參考對(duì)象,這里我們用較為熟悉的 Document 對(duì)象對(duì) With 語句舉例。例如 當(dāng)使用與 Document 對(duì)象有關(guān)的 write( )或 writeln( )方法時(shí),往往使用如下形式:document.writeln(”Hello!“)如果需要顯示大量數(shù)據(jù)時(shí),就會(huì)多次使用同樣的 document.writeln()語句,這時(shí)就可以像下面的程序那樣,把所有以 Document 對(duì)象為參考對(duì)象的語句放到With 語句塊中,從而達(dá)到減少語句量的目的。下面是一個(gè)With 語句使用的例子:<html><head><title>JavaScript Unleashed</title></head><body><script type="text/javascript"><!—with(document){write("您好 !");write("<br>這個(gè)文檔的標(biāo)題是 : /"" + title + "/".");write("<br>這個(gè)文檔的 URL 是: " + URL);write("<br>現(xiàn)在您不用每次都寫出 document 對(duì)象的前綴了 !");}// --></script></body></html>
這樣,您在使用 document 的方法和屬性時(shí)就可以去掉 Document 前綴。
新聞熱點(diǎn)
疑難解答
圖片精選