2015-11-05 138 views
1

任何人都可以告訴我下面的JavaScript中的空字符串檢查有什麼問題。在onClick函數中JavaScript檢查字符串是否爲空

它工作正常,如果我刪除檢查爲空字符串的代碼行,但我想顯示「沒有選擇」,如果選擇是空的。

<html> 
    <script language="JavaScript"> 
    <!-- 
    function update() 
    { 
    var selection = ""; 
    var empty = ""; 
    if (document.form1.TeaName.checked) selection += "Tea<br>"; 
    if (document.form1.CoffeeName.checked) selection += "Coffee<br>"; 
    if (document.form1.EggsName.checked) selection += "Eggs<br>"; 
    if (document.form1.BaconName.checked) selection += "Bacon<br>"; 
    if (selection.equals(empty)) selection = "Nothing selected."; 
    document.getElementById("currentSelection").innerHTML = selection; 
    } 
    --> 
    </script> 
    <body> 
    <form name="form1"> 
     <div id="container" style="width:100%"> 
     <div id="left" style="float:left; width: 30%;"> 
      <h3>List 1</h3> 
      <input type="checkbox" onClick="update()" name="TeaName" value="Tea">Tea<br> 
      <input type="checkbox" onClick="update()" name="CoffeeName" value="Coffee">Coffee<br> 
     </div> 
     <div id="middle" style="float:left; width: 30%;"> 
      <h3>List 2</h3> 
      <input type="checkbox" onClick="update()" name="EggsName" value="Eggs">Eggs<br> 
      <input type="checkbox" onClick="update()" name="BaconName" value="Bacon">Bacon<br> 
     </div> 
     <div id="right" style="float:left; width: 30%;"> 
      <h3>Currently selected</h3> 
      <p id="currentSelection">Please make a selection.</p> 
     </div> 
     </div> 
    </form> 
    </body> 
</html> 

謝謝您的時間,

詹姆斯

回答

3

有沒有這樣的方法equals。不要複雜的事情:

if (selection.length === 0) selection = "Nothing selected."; 
2

替換該行:

if (selection.equals(empty)) selection = "Nothing selected."; 

與此:

if (selection == "") selection = "Nothing selected."; 
0

試試這個

if(!selection) selection="Nothing selected."; 
0

沒有在相等javascript函數,你要麼檢查長度或一個簡單的===運算符

if (selection.length<= 0) selection = "Nothing selected."; 

       (OR) 

if(selection === "") selection = "Nothing selected"; 

       (OR) 

selection=(selection.length > 0) ? selection : "Nothing selected"; 

函數等於你用過的應該與某些javascript庫或框架有關。

0

您可以簡單地使用默認文本並跳過上次檢查。

var selection = "Nothing selected."; //default text 
// your rest of the code. 

OR

最後檢查是可以做到

selection = selection || "Nothing selected.";