[英]Add new elements to a javascript object dynamically
I'm trying to do a page with HTML and JQuery. 我正在尝试使用HTML和JQuery创建页面。 What I want to do with this is typing an e-mail in a textbox and when a button is pressed, add him to an object, and show the new e-mail added and the ones already sent.
我要执行的操作是在文本框中键入电子邮件,然后按按钮,将其添加到对象中,并显示添加的新电子邮件和已发送的电子邮件。 My problem is that the new e-mail replace the one I had, It's not added after it.
我的问题是,新电子邮件替换了我的电子邮件,之后没有添加。 How can I solve it?
我该如何解决?
Here's my code 这是我的代码
enter code here
<html>
<head>
<script src="config/jquery-1.8.3.min.js"></script>
<script type="text/javascript" language="javascript">
var obj = {};
$(document).ready(function(){
$('#agr').click(function(){
var correo_val = $('#correoe').val();
var estrc = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(correo_val == ''){
alert("Debes agregar un correo");
}
else if(!estrc.test(correo_val)){
alert("Correo no valido");
}
else if(estrc.test(correo_val)){
alert("Correo agregado exitosamente");
if(!obj.hasOwnProperty(correo_val)){
arr = [];
arr.push(correo_val);
// obj=arr;
obj2 = {};
obj2 = arr;
obj = obj2;
}else{
obj2 = {};
obj = obj2;
}
alert(obj);
$("#listac").html(obj);
}
});
});
</script>
</head>
<body>
<div>
<table style='margin-top:10%' align='center'>
<tr> <td> Ingresar correo electrónico </td> </tr>
<tr> <td> <input type='text' name='correoe' id='correoe'> </td> </tr>
<tr> <td> <input type='button' name='agregar' value='agregar' id='agr'> </td> </tr>
</table>
</div>
<div style="background:#FFFFFF;border:0" class="box" id="LCriterios">
<h1><span id="field"></span><span style="float:right;"></span></h1>
<!--<label><span>Tipo de operación</b></span><select class='opSelect' name='selOp' id='selOp'></select></label>
<label id='selCriterio'></label>
<label style="height: 30px;"><input type="button" class="btAgregar" value="Agregar" id="btn_add"/></label>-->
<label id="label12">Correos electrónicos </label>
<div id='listac'></div>
</div>
</body>
I've just made a Fiddle with one adjustment of your javascript - 我只是做了一个小提琴与你的JavaScript的一个调整-
if(!obj.hasOwnProperty(correo_val)){
arr = []; // <-- move this to the first line where
// you already have var obj = {};
arr.push(correo_val);
...
Move the arr = [];
移动
arr = [];
that you use to store the valid emails from this if()
clause to the first line of your code where you also declared var obj = {};
您用来将有效的电子邮件从该
if()
子句存储到代码的第一行的地方,在该行中您还声明了var obj = {};
. 。 Otherwise
arr = [];
否则
arr = [];
will be an empty array every time before you add another email and always have only one element (the last email that was added). 每次添加另一封电子邮件之前,它将为一个空数组,并且始终只有一个元素(添加的最后一封电子邮件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.