有人用js实现了吗?我的不知道为什么实现不了。
var getDOM = function(id){ return document.getElementById(id); } var addEvent = function(id,event,fn){ var el = getDOM(id) || document; if (el.addEventListener) { el.addEventListener(event,fn,false); } else if(el.attachEvent) { al.attachEvent('on'+event,fn); } } var getElementLeft = function(element){ var actualLeft = element.offsetLeft; var current = element.offsetParent; while(current !== null){ actualLeft += current.offsetLeft; current = current.offsetParent; } return actualLeft; } var getElementTop = function(element){ var actualTop = element.offsetTop; var current = element.offsetParent; while(current !== null){ actualTop += current.offsetTop; current = current.offsetParent; } return actualTop; } /*ajax*/ var ajaxGet = function(url,callback){ var _xhr = null; if(window.XMLHttpRequest){ _xhr = new window.XMLHttpRequest(); //非IE }else if(window.ActiveXObject){ _xhr = new ActiveXObject("Msxml2.XMLHTTP"); //IE下 } _xhr.onreadystatechange = function(){ if(_xhr.readyState == 4 && _xhr.status == 200){ alert(11); callback(JSON.parse(_xhr.responseText)); } } _xhr.open('get',url,false); _xhr.send(null); } /*事件代理*/ var delegateEvent = function(target,event,fn){ addEvent(document,event,function(e){ if(e.target.nodeName == target.toUpperCase()){ fn.call(e.target); } }); } /*主体*/ addEvent('search-input','keyup',function(){ var searchText = getDOM('search-input').value; ajaxGet('http://api.bing.com/qsonhs.aspx?q='+searchText,function(v){ var d = v.AS.Results[0].Suggests; var html = ''; for (var i = 0; i < d.length; i++) { html += '<li>'+d[i].Txt+'</li>'; } getDOM('search-result').innerHTML = html; getDOM('search-suggest').style.top = getElementTop(getDOM('search-form'))+38+'px'; getDOM('search-suggest').style.left = getElementLeft(getDOM('search-form'))+'px'; getDOM('search-suggest').style.position = 'absolute'; getDOM('search-suggest').style.display = 'block'; }); }); delegateEvent('li','click',function(){ var keyword = this.innerHTML; location.href = 'http://cn.bing.com/search?q='+keyword; });
在搜索框输入字符,调试显示
js-script.js:47 XMLHttpRequest cannot load http://api.bing.com/qsonhs.aspx?q=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.ajaxGet @ js-script.js:47(anonymous function) @ js-script.js:60 js-script.js:47 Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://api.bing.com/qsonhs.aspx?q=1'.