点击(此处)折叠或打开
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Address Book</title>
- <style>
- .active { background: #ddd; }
- .hovering { background: #eee; }
- form > div { padding: 10px; }
- </style>
- </head>
- <body>
- <h1>Address Book</h1>
- <form action="" method="get" id="search-form">
- <div class="section">
- <label for="q">Search address book</label>
- <input type="search" id="q" name="q" required placeholder="type a name">
- </div>
- <div class="button-group">
- <button type="submit" id="btn-search">search</button>
- <button type="button" id="get-all">get all contacts</button>
- </div>
- </form>
- <div id="output"></div>
- </body>
- </html>
- <script>
- var contacts = {
- "addressBook":[
- {
- "name":"helle",
- "email":"[email protected]",
- },
- {
- "name":"helle1",
- "email":"[email protected]",
- },
- {
- "name":"helle2",
- "email":"[email protected]",
- },
- {
- "name":"helle3",
- "email":"[email protected]",
- },
- {
- "name":"helle4",
- "email":"[email protected]",
- }
- ]
- };
- var searchField = document.getElementById("q");
- var adr = {
- search:function(event){
- event.preventDefault();
- var target = document.getElementById("output");
-
- var searchValue = searchField.value;
- var book = contacts.addressBook;
- var count = book.length;
- var i;
- target.innerHTML = "";
- if(count>0&&searchValue !== ""){
- for(i=0;i<count;i+=1){
- var obj = contacts.addressBook[i],
-
- isItFound = obj.name.indexOf(searchValue);
- //console.log(obj);
- if(isItFound !== -1){
- target.innerHTML += '
'+obj.name +','+obj.email+'
'; - }
- }
- }
- }
- }
- var searchForm = document.getElementById("search-form");
- searchField.addEventListener("submit",adr.search,false);
- var btn = document.getElementById("get-all");
- // activate the click event on your button
- btn.addEventListener("click", adr.search, false);
- </script>