2016-03-02 71 views

回答

1

一種方法是

var contacts = ["[email protected]", "[email protected]"], 
     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); 
    } 
    }) 

Check Codepen

1

您可以使用form元素,required屬性,onsubmit事件,event.preventDefault()Array.prototype.push()Array.prototype.forEach()input type="email"元素,.innerHTML

var contacts = ["[email protected]", "[email protected]"], 
 
    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>

做同樣的
+0

我明白這一點。我想知道如何在提交時將用戶輸入追加到聯繫人列表中。 – JordanBarber

+1

在帖子後面查看第3行和第4行 – guest271314

+0

這不收集用戶在提交時的輸入? – JordanBarber