使用javascript对项目列表进行排序
我正在完成一项课堂作业,其中我需要完成以下内容: 1用户在文本框表单字段中键入项目列表 2当用户按下排序按钮时,文本框中的列表将被排序 3它从文本框中提取文本,并将排序后的文本放回文本框中 请帮忙 编辑:这是我到目前为止所做的,但它不起作用。谢谢各位使用javascript对项目列表进行排序,javascript,sorting,Javascript,Sorting,我正在完成一项课堂作业,其中我需要完成以下内容: 1用户在文本框表单字段中键入项目列表 2当用户按下排序按钮时,文本框中的列表将被排序 3它从文本框中提取文本,并将排序后的文本放回文本框中 请帮忙 编辑:这是我到目前为止所做的,但它不起作用。谢谢各位 <script type="text/javascript"> function addName() { var name2add = document.nameForm.newName.value; /
<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>
幸运的是,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的文本框。您当前拥有的任何代码都会对您有所帮助。因为我们不是来做你的家庭作业的。你自己做你的家庭作业-当你卡住的时候问-张贴你写的代码。我们会帮你做作业;我们不会为你做家庭作业。