0

まず、私は JavaScript の初心者なので、私の無知を許してください。3 つの関数を持ち、配列も使用するフォームを作成しています。入力された (アラート ボックス内) リスト - 入力された名前 (アラート ボックス内) を一覧表示します。

私はリスト機能を持っています(良い)。名前を入力した後、およびフィールドを空白のままにしておくと(良くない)、名前を入力するようにというアラートが表示され、検索機能がまったく機能しません。私のコードは以下のとおりです。私は非常に多くの反復を試み、非常に多くのサイトでヘルプを検索しました。また、firebug も試しました。誰かが私を正しい方向に向けてくれることを願っています。無題

<body>
<script type="text/javascript">
  var a = new Array();

  function list() {
      var s = "";
      for (i = 0; i < a.length; i++)
          s = s + a[i] + "\n";
      alert(s);
  }

  function add() {
      // If the text box empty you ask the user to enter a name.
      var myTextField = document.getElementById("myText");
      a[a.length] = myTextField.value;
      myTextField.value = "";
      if (myTextField.value == "") {
          alert("Please enter a name");
          return false;
      }

      function find() {
          //If the name already exists you should get a warning
          var myTextField = document.getElementById("myText");
          a[a.length] = myTextField.value;
          myTextField.value = "";
          for (var i = 0; i < a.length; i++)
              if (a[i] == myTextField) {
                  alert("Sorry, the name " + a[i] + " already exists.  Try again");
              }
      }
  }

</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
4

2 に答える 2

0

あなたはそれをほとんどやったが、いくつかのlilエラー..ここでjsfiddleを確認することができます

HTML:

<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>

JS:

$(".add_button").live("click", function(){
    add()
});

$(".list_button").live("click", function(){
    list()
});

$(".find_button").live("click", function(){
    find()
});


var a = new Array();
function list()
{
    var s = "";
    for(i = 0; i < a.length; i++)
    s = s + a[i] + "\n";
    alert(s);
 }

function add()
{
   // If the text box empty you ask the user to enter a name.
    var myTextField = document.getElementById("myText");
    a[a.length] = myTextField.value;

    if (myTextField.value == "")
    {
        alert ("Please enter a name");
        return false;
    }
    myTextField.value = "";
}

function find()
{
    //If the name already exists you should get a warning
    var status = true;
    var myTextField = document.getElementById("myText");

    for (var i = 0; i < a.length; i++)
    {
        if (a[i] == myTextField.value)
        {
            alert ("Sorry, the name " + a[i] + " already exists.  Try again");
            status = false;
            break;
        }
    }
    if(status==true)
    {
        a[a.length] = myTextField.value;
    }
    myTextField.value = "";
}
于 2013-11-02T19:30:27.910 に答える