使用纯 JS 提交时将数据添加到 DOM
Adding data to DOM on submit with pure JS
有人可以告诉我用这个js实现同样的事情的最佳方法是什么:
function ContactController($scope) {
$scope.contacts = ["hi@me.no", "hi@you.com"];
$scope.addMail = function() {
if(this.mailAdress) {
$scope.contacts.push($scope.mailAdress);
$scope.mailAdress = "";
}
};
}
不使用角度。 我只是想学习如何使用 javascript 将用户输入保存到 DOM。 谢谢!
做同样事情的一种方法是
var contacts = ["hi@me.no", "hi@you.com"],
ul = document.querySelectorAll('.email-list')[0];
// Iterate over the contacts and append it to the ul
for (var i = 0; i < contacts.length; i++) {
addEmailToContacts(contacts[i]);
}
function addEmailToContacts(contact) {
var li = document.createElement('li');
li.innerHTML = contact;
ul.appendChild(li);
};
// Click event for the submit
document.querySelector('#submit').addEventListener('click', function(e) {
e.preventDefault();
// Get the value
var value = document.querySelectorAll('input[type="mail"]')[0].value;
if (value) {
addEmailToContacts(value);
}
})
检查代码笔
您可以使用
form
元素,input type="email"
具有required
属性的元素,onsubmit
事件,event.preventDefault()
,Array.prototype.push()
,Array.prototype.forEach()
,.innerHTML
var contacts = ["hi@me.no", "hi@you.com"],
div = document.getElementById("update");
function updateContacts() {
div.innerHTML = "";
contacts.forEach(function(address) {
div.innerHTML += address + "<br>"
})
}
updateContacts();
document.forms[0].onsubmit = function(event) {
event.preventDefault();
// user input to update `contacts` array
contacts.push(this["input"].value);
// display updated `contacts` array
updateContacts();
}
<div id="update">
</div>
<form>
<input name="input" type="email" required />
<input type="submit" />
</form>
相关文章:
- javascript函数将数据添加到屏幕,但随后被另一个函数覆盖
- 将嵌套对象数据添加到窗体中
- 挖空.js - 向服务器端发送的数据添加属性
- 如何将数据添加到json的子节点
- 无法将 json 数据添加到 pyjade 中的数据属性
- 通过变量将数据添加到图形中
- 预先构建的GUI,用于上传.csv并将数据添加到mysql数据库
- Fullcalendar-我们可以将自定义数据添加到我们的活动Json数据中吗
- 将多个csv文件中的时间戳数据添加到highchart中
- 将文本框中的数据添加到表Javascript、HTML中
- 无法使用asp.net mvc将数据添加到数据库中
- 用javascript将数据添加到对象数组中
- 我该如何将自己的数据添加到响应迅速的美国各州地图中
- 在$.ajax调用中将附加数据添加到jQuery包装的对象数据中
- 将新的系列[0]数据添加到现有的高位图表中
- 为高图实时数据添加一个附加点
- 如何在D3中为用于显示饼图的数据添加键
- CSS 为 JSON 数据添加两行字符
- 将数据添加到 ko.observablearray 的末尾
- 向数据表中的 json 数据添加文本