点击(此处)折叠或打开
- <!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><!--/.section-->
- <div class="button-group">
- <button type="submit" id="btn-search">search</button>
- <button type="button" id="get-all">get all contacts</button>
- </div><!--/.button-group-->
- </form>
- <div id="output"></div><!--/#output-->
- <!-- Keeping JS at the bottom, because we rock at performance -->
- </body>
- </html>
- <script>
- (function(){
- 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 searchForm = document.getElementById("search-form"),
- searchField = document.getElementById("q"),
- getAllButton = document.getElementById("get-all"),
- count = contacts.addressBook.length,
- target = document.getElementById("output");
- var addr = {
- search:function(event){
- var searchValue = searchField.value,
- i;
- event.preventDefault();
- target.innerHTML = "";
- if(count>0&&searchValue !== ""){
- for(i=0;i<count;i+=1){
- var obj = contacts.addressBook[i],
- ifItFound = obj.name.indexOf(searchValue);
- if(ifItFound !== -1){
- target.innerHTML += "
"
+obj.name+''+obj.email+''; - }
- }
- }
- },getAllContacts:function(){
- var searchValue = searchField.value,
- i;
- target.innerHTML = "";
- if(count>0){
- for(i=0;i<count;i+=1){
- var obj = contacts.addressBook[i],
- ifItFound = obj.name.indexOf(searchValue);
- if(ifItFound !== -1){
- target.innerHTML += "
"
+obj.name+''+obj.email+''; - }
- }
- }
- },setActiveSection:function(){
- this.parentNode.setAttribute("class","active");
- },removeActiveSection:function(){
- this.parentNode.removeAttribute("class");
- },addHoverClass:function(){
- searchForm.setAttribute("class","hovering");
- },removeHoverClass:function(){
- searchForm.removeAttribute("class");
- }
- }
- searchField.addEventListener("keyup",addr.search,false);
- searchField.addEventListener("focus",addr.setActiveSection,false);
- searchField.addEventListener("blur",addr.removeActiveSection,false);
- getAllButton.addEventListener("click",addr.getAllContacts,false);
- searchForm.addEventListener("mouseover",addr.addHoverClass,false);
- searchForm.addEventListener("mouseout",addr.removeHoverClass,false);
- searchForm.addEventListener("submit",addr.search,false);
- })();
-
-
- </script>