JavaScript检查onClick函数

时间:2015-11-05 23:42:45

标签: javascript html

任何人都可以告诉我下面的JavaScript中的空字符串检查有什么问题。

如果我删除检查空String的代码行,它可以正常工作,但我想显示"没有选择"如果选择为空。

<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>

感谢您的时间,

詹姆斯

5 个答案:

答案 0 :(得分:3)

没有这样的方法equals。不要让事情复杂化:

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

答案 1 :(得分:2)

替换此行:

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

用这个:

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

答案 2 :(得分:0)

试试这个

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

答案 3 :(得分:0)

javascript中没有equals函数,你要么检查长度还是简单的===运算符

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

               (OR)

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

              (OR)

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

您使用过的函数应与某些javascript库或框架相关。

答案 4 :(得分:0)

您可以使用默认文本并跳过上一次检查。

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

OR

上次检查可以

完成
selection = selection || "Nothing selected.";