2010-06-09 54 views
1

我在課堂作業的工作中,我需要完成下列項目列表:排序使用JavaScript

1用戶類型的項目列表到一個文本框(表單字段) 2當用戶按下排序按鈕,文本框中的列表被排序 3它從文本框中取出文本並將排序後的文本放回文本框中

請幫忙!

編輯:這是我迄今爲止,它不是工作,雖然。多謝你們。

<script type="text/javascript"> 
    function addName() 
    { 
    var name2add = document.nameForm.newName.value; 
    // is the name 1-15 characters in length? 
    if (name2add.length > 15 || name2add.length == 0) 
    { 
     // no, warn the user 
     alert("Name must be between 1 and 15 characters long."); 
     // put the focus and selection back in the name text box 
     document.nameForm.newName.focus(); 
     document.nameForm.newName.select(); 
    } else { 
     theSelect = document.nameForm.nameList; 
     newVal = theSelect.options.length; 
     //alert(name2add + " will be #" + newVal); 
     // crate the new Option object to insert into the list 
     var newOption = new Option(name2add,newVal); 
     // insert the new option into the list 
     theSelect.options[newVal] = newOption; 
     // clear out the name text field and return the focus there 
     document.nameForm.newName.value = ""; 
     document.nameForm.newName.focus(); 
    } 
    return; 
    } 
    function deleteName() 
    { 
     var theSelect = document.nameForm.nameList; 
     theSelect.options[theSelect.selectedIndex] = null; 
     return; 
    } 
    </script> 

    </head> 

    <body> 
    <form id="form4" name="nameForm" method="post" action=""> 
     <p> 
     <label> 
      <input type="text" name="newName" id="newName" /> 
     </label> 
     </p> 
     <p> 
      <input type="button" value="Add Name To List" name="addButton" id="addButton" onclick="addName()" /> 

     </p> 
     <p> 
     <label> 
      <select name="list" size="3" id="nameList" > 
      </select> 
     </label> 
     </p> 
    <p> 
    <INPUT TYPE="BUTTON" NAME="sort" VALUE=" Sort " 
    OnClick="sortOptions(document.nameForm.list)"> 
    </p> 
    <p> 
    <input type="button" value="Remove Name From List" name="deleteButton" id="deleteButton" onclick="deleteName()" /> 
    </p> 
    </form> 
+8

您目前擁有的任何代碼都會對您有所幫助。因爲我們不是在這裏做你的功課。 – 2010-06-09 03:51:57

+1

自己做家庭作業 - 詢問你什麼時候卡住了 - 發佈你寫的代碼。我們會幫你做功課;我們不會爲你做你的功課。 – Amarghosh 2010-06-09 04:01:16

回答

0

幸運的是,Javascript提供了一個本機排序算法,所以你不必自己寫一個。它是array.sort()。

所以,基本上,從文本框中獲取文本,將文本放入數組中。然後,在數組上運行.sort()然後將其放回文本框中。

至於將文本轉換爲數組,如果用逗號分隔,可以使用string.split(「\ n」),或者用string.split(「,」)分隔。

var itemsToSort = document.getElementById("text_box") 
var arrayToSort = itemsToSort.split("\n") 
arrayToSort.sort() 
document.getElementById("text_box").value = arrayToSort.join("\n") 

您的文本框的ID爲「text_box」。