如何安排阵列

时间:2017-02-02 14:02:32

标签: javascript arrays

如果有人可以查看我的代码,那将非常有用,因为我对JS和HTML都很陌生。

我正在尝试按字母顺序对数组进行排序,我已经查看了其他线程来回答这个问题,而我的代码似乎并不适合其中任何一个。所以,如果somone可以帮我订购代码,我将不胜感激......



var products = ["Printer", "Tablet", "Router", "Phone", "Xbox", "Laptop"];
document.getElementById("Mylist").innerHTML = products;

function myFunction() {
  products.sort();
  document.getElementById("Mylist").innerHTML = products;
}

<button onclick="list">Click to Arrange</button>

<p id="Mylist"></p>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

你应该调用“myFunction()”

var products = ["Printer", "Tablet", "Router", "phone", "Xbox", "Laptop"];
document.getElementById("Mylist").innerHTML = products;

function myFunction() {
  products = products.sort();
  document.getElementById("Mylist").innerHTML = products;
}
<button onclick="myFunction()">Click to Arrange</button>

<p id="Mylist"></p>

答案 1 :(得分:0)

您必须在HTML按钮属性myFunction()中使用您的命名函数onclick,如下所示

var products = ["Printer", "Tablet", "Router", "phone", "Xbox", "Laptop"];
document.getElementById("Mylist").innerHTML = products;

function myFunction() {
  products.sort();
  document.getElementById("Mylist").innerHTML = products;
}
<button onclick="myFunction()">Click to Arrange</button>

<p id="Mylist"></p>

答案 2 :(得分:0)

以下是如何首先显示列表然后再排序和显示。

您需要致电myFunction()而不是list

var products = ["Printer", "Tablet", "Router", "phone", "Xbox", "Laptop"];

window.onload=function() { // now the elements exists on the page
  document.getElementById("Mylist").innerHTML = products;
}

function myFunction() {
  products.sort();
  document.getElementById("Mylist").innerHTML = products;
}
<button onclick="myFunction()">Click to Arrange</button>

<p id="Mylist"></p>