[英]Javascript: how do I take my users input data and turn it into an object?
I have a to-do list that I want I can receive user input on via html text boxes. 我有一个待办事项清单,希望我可以通过html文本框接收用户输入。 The information is currently printed under these text boxes in an un-ordered list form after a button is clicked.
单击按钮后,当前信息以无序列表形式打印在这些文本框下。
Its not perfect, that said I skipped a step, I want to take the strings the user inputs with button click and add them first to this function. 这并不完美,也就是说我跳过了一步,我想通过单击按钮获取用户输入的字符串,然后将其首先添加到此功能中。
function task(task_text, date, time)
The purpose of this of course is to trade the objects properties throughout the code later. 当然,这样做的目的是稍后在整个代码中交换对象属性。
So, how would I go about taking the information in the text boxes and submit it to the above function on click of the button? 那么,我将如何处理文本框中的信息,然后单击按钮将其提交给上述功能?
The Fiddle http://jsfiddle.net/brendanjackson/j501hc1k/1/ 小提琴http://jsfiddle.net/brendanjackson/j501hc1k/1/
To get this input into the function you must listen for the onclick event. 要将此输入输入到函数中,您必须侦听onclick事件。
var input_text = document.getElementById('input_text').value;
var input_date = document.getElementById('input_date').value;
var input_time = document.getElementById('input_time').value;
onclick="task(input_text, input_date, input_time);"
how do I take my users input data and turn it into an object? 如何让用户输入数据并将其转换为对象?
When your function is called, you can then create an object from the data passed in, like so: 调用函数时,可以根据传入的数据创建对象,如下所示:
var inputs = [];
function task(task_text, date, time) {
input.push({
task_text: task_text,
date: date,
time: time
});
}
or if you are only planning to accept one input, you could just do this: 或者,如果您仅打算接受一个输入,则可以执行以下操作:
var obj = {};
function task(task_text, date, time) {
obj.task_text: task_text,
obj.date: date,
obj.time: time
}
Fiddle: http://jsfiddle.net/KyleMuir/3rh4u7qu/1/ 小提琴: http : //jsfiddle.net/KyleMuir/3rh4u7qu/1/
I think this is what you're after: 我认为这是您追求的目标:
function task(text, date, time) {
this.text = text;
this.date = date;
this.time = time;
}
function buttonClicked() {
var myText = document.getElementById('myText');
var input_text = document.getElementById('input_text').value ;
var input_date = document.getElementById('input_date').value ;
var input_time = document.getElementById('input_time').value ;
var item = new task(input_text, input_date, input_time);
myText.innerHTML += "<li>"+item.text+" "+item.date+" "+item.time+"</li>";
}
Also, added a slightly more interesting use of your task object here which might be useful from a learning perspective: http://jsfiddle.net/KyleMuir/3rh4u7qu/2/ 另外,在此处添加了对任务对象的更有趣的用法,从学习的角度来看这可能很有用: http : //jsfiddle.net/KyleMuir/3rh4u7qu/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.