Home >Web Front-end >JS Tutorial >Sample code sharing of input box and candidate box in JavaScript component development

Sample code sharing of input box and candidate box in JavaScript component development

黄舟
黄舟Original
2017-03-21 14:30:341300browse

This article will share with you the example code of input box and candidate box developed based on js component. The code is simple and easy to understand, very good, and has reference value. Friends who need it can refer to it

1. Compatible with ie8, mainly eventscompatible

var EventUtil = {
   on:function(elem,type,handler){
    if(elem.addEventListener){
     elem.addEventListener(type,handler,false);
    }else if(elem.attachEvent){
     elem.attachEvent("on"+type,handler);
    }
   },
   getEvent:function(event){
    return event||window.event;
   },
   getTarget:function(event){
    return event.target||event.srcElement;
   },
   getCharCode:function(event){
    if(typeof event.handler == "number"){
     return event.charCode;
    }else{
     return event.keyCode;
    }
   }
  }

2. Use event proxy for the content in the candidate box, and click on the blank space to disappear

EventUtil.on(document.body,'click',function(e){
   stopPropagation(e);
   if(EventUtil.getTarget(e).nodeName=='BODY'){
    datalist.style.visibility = 'hidden';
    datalist.innerHTML ='';
   }
   if(EventUtil.getTarget(e).nodeName == "LI"){
    input.value = EventUtil.getTarget(e).innerHTML;
    datalist.style.visibility = 'hidden';
    datalist.innerHTML ='';
   }
  })

3. Prevent bubbling in compatibility mode

 function stopPropagation(e){
   e = window.event||e;
   if(document.all){
    e.cancelBubble = true;
   }else{
    e.stopPropagation();
   }
  }

4. Rendering

Sample code sharing of input box and candidate box in JavaScript component development

5. Complete code



 
  
  
  
 
 
 

The above is the detailed content of Sample code sharing of input box and candidate box in JavaScript component development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn