【问题标题】:need to add 2 textbox so that user can type in and add to arrays需要添加 2 个文本框,以便用户可以输入并添加到数组
【发布时间】:2012-12-12 21:36:37
【问题描述】:

好的,所以我有 2 个数组,我必须在 html javascript 中添加一个 gui,它允许用户输入新的国家和人口,并有一个按钮可以将新元素添加到数组中。我该怎么做?

<head>
<title></title>
<script type="text/javascript">

    var countries = new Array();
    countries[0] = "Nigeria";
    countries[1] = "Irag";
    countries[2] = "Philippines";
    countries[3] = "Indonesia";
    countries[4] = "Egypt";
    countries[5] = "Russia";
    countries[6] = "Vietnam";
    countries[7] = "Ethiopia";
    countries[8] = "Mexico";

    var population = new Array();
    population[0] = "166,629,000";
    population[1] = "33,330,000";
    population[2] = "92,337,000";
    population[3] = "237,641,000";
    population[4] = "82,940,000";
    population[5] = "143,300,000";
    population[6] = "87,840,000";
    population[7] = "84,320,000";
    population[8] = "112,336,000";

</script>

【问题讨论】:

  • 你实际尝试过什么?

标签: javascript html arrays button textbox


【解决方案1】:

这应该可以解决问题:

//Easier way to define and populate an array
var countries =
[
    "Nigeria",
    "Iraq",
    "Philippines",
    //And so on
];

//Same for population

//Function to add the new data
function addData()
{
    //push() adds an element at the end of an array
    countries.push(document.getElementById("myCountry").value);
    population.push(document.getElementById("myPopulation").value);
}

//Add the click event
document.getElementById("myButton").onclick = addData;

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多