2013-06-27 73 views
0

我在做什麼錯了?我正在嘗試將textID值設置爲空。JavaScript將文本字段設置爲空時隱藏它

function toggle_visibility(id,textid) { 
     var e = document.getElementById(id); 
     var f = document.getElementById(textid); 
     if(e.style.display == 'block') 
      e.style.display = 'none'; 
      f.value=""; 
     else 
      e.style.display = 'block'; 
    } 

我相信它一定是簡單的。

+1

[瞭解如何** **調試JavaScript的(http://www.netmagazine.com/tutorials/javascript-debugging-beginners)。 –

+0

(因爲那樣你會看到錯誤'SyntaxError:Unexpected token else')。 –

回答

5

if語句結束後;如果你不把它放在括號{}

正確的,如果其他人:

if (e.style.display == 'block') { // Multi-line. 
     e.style.display = 'none'; 
     f.value=""; 
    } 
    else 
     e.style.display = 'block'; // Single-line. 
+1

可能值得注意的是,如果沒有括號可用於單行if else語句,可能是OP採用這種風格的地方。 – tymeJV

1

您必須添加括號來表示,所有的括號內的語句需要執行。否則,我認爲只有第一條語句被執行,所以該字段沒有被清除。

0

與NullPointerException類似,如果您不使用{ ... },則該語句在一條語句後結束。我認爲爲了清楚起見,最好的做法是始終使用括號,除非整個if .. else if ... else聲明是單線。

以下所有工作,但在我看來,中間和最後,更容易合作。

/* Hard to follow */ 
if (false) { // Do several things 
    console.log("Multi"); 
} 
else // Do one thing 
    console.log("Singe"); 


/* Easy to see what's related to what */ 
if (false) { 
    console.log("Multi_if"); 
} 
else{ 
    console.log("Multi_else"); 
} 


/* Reasonably clear to decipher */ 
if (false) 
    console.log("Single_if"); 
else 
    console.log("Singe_else"); 

http://jsfiddle.net/daCrosby/qGK7B/

相關問題