点击(此处)折叠或打开

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Address Book</title>
  6. <style>
  7. .active { background: #ddd; }
  8. .hovering { background: #eee; }
  9. form > div { padding: 10px; }
  10. </style>
  11. </head>
  12. <body>
  13. <h1>Address Book</h1>
  14. <form action="" method="get" id="search-form">
  15. <div class="section">
  16. <label for="q">Search address book</label>
  17. <input type="search" id="q" name="q" required placeholder="type a name">
  18. </div>
  19. <div class="button-group">
  20. <button type="submit" id="btn-search">search</button>
  21. <button type="button" id="get-all">get all contacts</button>
  22. </div>
  23. </form>
  24. <div id="output"></div>

  25. </body>
  26. </html>
  27. <script>
  28.    var contacts = {
  29.        "addressBook":[
  30.      {
  31.          "name":"helle",
  32.              "email":"[email protected]",
  33.          },
  34.          {
  35.          "name":"helle1",
  36.              "email":"[email protected]",
  37.          },
  38.          {
  39.          "name":"helle2",
  40.              "email":"[email protected]",
  41.          },
  42.          {
  43.          "name":"helle3",
  44.              "email":"[email protected]",
  45.          },
  46.          {
  47.          "name":"helle4",
  48.              "email":"[email protected]",
  49.          }
  50.      ]
  51.    };
  52.   var searchField = document.getElementById("q");
  53.    var adr = {
  54.       search:function(event){
  55.      event.preventDefault();
  56.         var target = document.getElementById("output");
  57.         
  58.         var searchValue = searchField.value;
  59.         var book = contacts.addressBook;
  60.         var count = book.length;
  61.         var i;
  62.         target.innerHTML = "";
  63.         if(count>0&&searchValue !== ""){
  64.          for(i=0;i<count;i+=1){
  65.          var obj = contacts.addressBook[i],
  66.             
  67.              isItFound = obj.name.indexOf(searchValue);
  68.              //console.log(obj);
  69.              if(isItFound !== -1){
  70.              target.innerHTML += '

    '+obj.name +','+obj.email+'

    '
    ;
  71.              }
  72.          }
  73.         }
  74.      }
  75.    }
  76.    var searchForm = document.getElementById("search-form");
  77.    searchField.addEventListener("submit",adr.search,false);
  78.    var btn = document.getElementById("get-all");
  79. // activate the click event on your button
  80. btn.addEventListener("click", adr.search, false);
  81. </script>

10-20 17:43