Javascript 将用户输入存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10523200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:41:56  来源:igfitidea点击:

storing user input in array

javascriptarraysforms

提问by Diego Esquibel

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!

我需要执行以下操作(我是编程初学者,所以请原谅我的无知): 我必须向用户询问表单上三个不同文本框中的三个不同信息。然后用户有一个名为“输入”的按钮,当他点击它时,他在三个字段上输入的文本应该存储在三个不同的数组中,在这个阶段我还想看到用户输入的检查数据实际上是否被存储在数组中。我一直试图让应用程序仅在其中一个阵列上存储或显示数据,但未成功。我有 2 个文件:film.html 和 functions.js。这是代码。任何帮助将不胜感激!

<html>
    <head>
    <title>Film info</title>

    <script src="jQuery.js" type="text/javascript"></script>
    <script src="functions.js" type="text/javascript"></script>

    </head>
        <body>

        <div id="form">

            <h1><b>Please enter data</b></h1>
        <hr size="3"/>
        <br>

            <label for="title">Title</label> <input id="title" type="text" > 
        <br>

            <label for="name">Actor</label><input id="name" type="text">
        <br>

            <label for="tickets">tickets</label><input id="tickets" type="text">
        <br>
        <br>

            <input type="button" value="Save" onclick="insert(this.form.title.value)">
            <input type="button" value="Show data" onclick="show()"> <br>

            <h2><b>Data:</b></h2>
        <hr>
        </div>

        <div id= "display">

        </div>
        </body>

</html>

var title=new Array();
var name=new Array();
var tickets=new Array();

function insert(val){
  title[title.length]=val;
  }

function show() {
  var string="<b>All Elements of the Array :</b><br>";
  for(i = 0; i < title.length; i++) {
  string =string+title[i]+"<br>";
  }
  if(title.length > 0)
 document.getElementById('myDiv').innerHTML = string;
  }

回答by Sampson

You're not actually going out after the values. You would need to gather them like this:

你实际上并不是在追求价值观。你需要像这样收集它们:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

您可以将所有这些放在一个数组中:

var myArray = [ title, name, tickets ];

Or many arrays:

或多个数组:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push()method to push new values onto it:

或者,如果数组已经存在,您可以使用他们的.push()方法将新值推送到它上面:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form>tags wrapping your fields:

您的保存按钮不起作用,因为您引用了this.form,但是页面上没有表单。为了使其工作,您需要将<form>标签包装在您的字段中:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

我做了一些更正,并将更改放在 jsbin 上:http://jsbin.com/ufanep/2/edit

The new form follows:

新表格如下:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclickattributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

还有一些改进的空间,例如删除onclick属性(这些绑定应该通过 JavaScript 完成,但这超出了本问题的范围)。

I've also made some changes to your JavaScript. I start by creating three empty arrays:

我还对您的 JavaScript 进行了一些更改。我首先创建三个空数组:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

现在我们有了这些,我们需要引用我们的输入字段。

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

我也得到了对我们的消息显示框的引用。

var messageBox  = document.getElementById("display");

The insert()function uses the references to each input field to get their value. It then uses the push()method on the respective arrays to put the current value into the array.

insert()函数使用对每个输入字段的引用来获取它们的值。然后它使用push()相应数组上的方法将当前值放入数组中。

Once it's done, it cals the clearAndShow()function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

完成后,它会clearAndShow()调用负责清除这些字段(使它们为下一轮输入做好准备)的函数,并显示三个数组的组合结果。

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .valueproperty of each input to an empty string. It then clears out the .innerHTMLof our message box. Lastly, it calls the join()method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

如前所述,此函数首先将.value每个输入的属性设置为空字符串。然后它会清除.innerHTML我们的消息框。最后,它调用join()我们所有数组上的方法将它们的值转换为逗号分隔的值列表。然后将此结果字符串传递到消息框中。

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

最终结果可以在线使用http://jsbin.com/ufanep/2/edit

回答by Icarus

You have at least these 3 issues:

您至少有以下 3 个问题:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id displayyet in your javascript you attempt to get element myDivwhich is not even defined in your markup.
  3. Nevername variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
  1. 您没有正确获取元素的值
  2. 您试图用来显示值是否已保存的 divdisplay在您的 javascript 中还具有 id ,您尝试获取myDiv甚至未在标记中定义的元素。
  3. 永远不要在 javascript 中使用保留关键字命名变量。在我能想到的大多数语言中,使用“字符串”作为变量名并不是一件好事。我将您的字符串变量重命名为“内容”。见下文。

You can save all three values at once by doing:

您可以通过执行以下操作一次保存所有三个值:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

然后将显示功能更改为:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddlefor you to play around.

这是一个jsfiddle供你玩。