2009-11-01 108 views
0

我有如下用的getElementById一個問題:問題與的getElementById

<script type="text/javascript"> 
<!-- 
function show_links(locale) { 

     var box = document.getElementById(locale); 

     if(box.style.display == "none") { 
      box.style.display = "inline"; 
     } 
     else { 

      box.style.display = "none"; 
     } 

    } 
    //--> 
</script> 

<div class="link"><strong><a href="javascript:show_links(test);">Test</a></strong></div> 
<div class="test"> Blah blah blah. This content comes and goes. </div> 

所以你有代碼。當我點擊鏈接「測試」時,它應該隱藏「等等等等文本」。當再次點擊時,它應該顯示。但是,我有一個奇怪的問題。我通過調試器處理了代碼,看起來var box = document.getElementById(locale);行不能正常工作。 box正被設置爲空。任何人都可以爲什麼理論化?

+0

把測試放在引號 – 2009-11-01 02:21:30

回答

3

你有幾個問題。首先是關鍵問題:

  1. 您傳遞給show_links函數的值是變量test。這相當於undefined,所以它不會匹配任何東西。
  2. 您試圖通過其ID找到的元素沒有ID。它只有一個班。

你需要給你試圖匹配一個ID的元素,並通過一個,而不是一個未定義的值。

然後是較小的問題。

  1. 您正在測試內聯顯示樣式屬性,但不是默認設置它。根據經驗,最好旋轉className屬性,並在樣式表中定義樣式。
  2. 您正在使用JavaScript僞URI而不是progressive enhancement
  3. 您有comments wrapped around the inside of the script。在最好,這些是毫無意義的。
  4. 您正在編輯inlinenone之間的div,但div的默認顯示值爲block。有理由有內聯格子,但大多數時候你應該使用另一個元素。
+0

+1。即使不考慮漸進式增強的好處,「javascript:」僞URI在他們出生的那一天被破壞和過時,永遠不會在頁面中使用。永遠。 – bobince 2009-11-01 02:54:56

0
javascript:show_links(test); 

test是一個未知的標識符。你在哪裏定義它?你的意思是喂一個字符串嗎?

<div class="test"> Blah blah blah. This content comes and goes. </div> 

此行中沒有標識爲test的元素。使用正確的屬性id