获取同一类的多个输入字段的值并添加到javascript对象中 [英] Getting value of multiple input fields with same class and adding into javascript object
问题描述
< input title =1type =textclass = 电子邮件 >
< input title =2type =textclass =email>
< input title =3type =textclass =email>
上面是我的html,我试图抓取每个输入框的电子邮件并将其存储在对象与标题作为关键。
这是我的JavaScript目前的样子
var emailObj = {};
$(input [class = email])。each(function(){
var id = $(this).attr(title);
var email = $(this).val()
emailObj [id] = email;
});
目前,console.log仅显示添加到对象的最后一个值,如下所示。
Object {3 =a@a.com}
我的预期结果应如下所示
Object {1 =a@a.com,2 =b@b.com,3 =c@c.com}
有人能为我解释一下这个问题吗?
感谢您阅读,
问候。
那里与您的代码无关。我建议你把它写成实用方法。
$ b $ pre $ function getValues(selector){
var tempValues = {} ;
$(selector).each(function(){
var th = $(this);
tempValues [th.attr('title')] = th.val();
});
return tempValues;
}
var values = getValues('。email');
或者如果您想将值存入数组
$('。email')。map(function(){return $(this).val();})。get();
.get()
会将其转换为一个常规的数组。
你写的代码是绝对正确的。但是,当我加载它返回给我空,因为在执行时,文本框中没有值。
I am faced with a issue as follows:
<input title="1" type="text" class="email">
<input title="2" type="text" class="email">
<input title="3" type="text" class="email">
Above is my html where I am trying to grab the emails of each input box and store it in an object with the title as key.
Here is what my JavaScript currently looks like
var emailObj = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val()
emailObj[id] = email;
});
Currently console.log displays only the last value added to the object as shown below.
Object { 3="a@a.com"}
Where my expected result should be as show below
Object { 1="a@a.com", 2="b@b.com", 3="c@c.com"}
Could someone shed some light on this issue for me please?
Thank you for reading, Regards.
There is no problem with your Code. And I would suggest you to write it as utility method
function getValues(selector){
var tempValues = {};
$(selector).each(function(){
var th= $(this);
tempValues[th.attr('title')] = th.val();
});
return tempValues;
}
var values = getValues('.email');
or If you want values into an array
$('.email').map( function(){return $(this).val(); }).get();
.get()
will convert it to a regular array.
The code you have written is absolutely correct. But when I have loaded it was returning me null, because at the time of execution, there were no values in textboxes.
这篇关于获取同一类的多个输入字段的值并添加到javascript对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!