一個類比搜尋自動補全的執行個體(超簡單),類比補全執行個體

來源:互聯網
上載者:User

一個類比搜尋自動補全的執行個體(超簡單),類比補全執行個體

      很早就像寫一個類比Google搜尋欄自動補全的執行個體,那時候剛學點js,css也玩不轉,即使網上有些demo,看起來也很費力。寫了兩次只是勉強能出來待篩選項,不能自由選擇。這兩天學了點jQuery的ajax,配合一點資料,自己成功實現了這個功能,jQuery的口號真是名副其實----The Write Less, Do More.


CSS

<style type="text/css" >.listbox{position: relative;left: 10px;margin: 10px;width: 200px;background-color: #000;color: #fff;border: 2px solid #000; }.nameslist{margin: 0px;padding: 0px;list-style: none;}.hover{background-color: cyan;color: red;}</style>

js

<script type="text/javascript">$(document).ready(function(){     $('.listbox').hide();     $('.userid').keyup(function(){    var user = $('.userid').val();    var data = 'username='+user;    $.ajax({        type:"POST",        url:"AutoServlet",        data:data, success:function(html){  $('.listbox').show();  $('.nameslist').html(html);  $('li').hover(  function(){    $(this).addClass('hover');  },  function(){   $(this).removeClass('hover');  }  );    $('li').click(function(){      $('.userid').val($(this).text());      $('.listbox').hide();    });    }});return false;});});</script>

HTML元素

<form>  <span class="label">Enter username</span>  <input type="text" name="userid" class="userid"/>  <div class="listbox">  <div class="nameslist">  </div>  </div></form>


後台servlet

/** * @author fcs * AutoComplete demo * 2014-10-25 */public class AutoServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String sname = request.getParameter("username");System.out.println("sname:"+sname);PrintWriter pw = response.getWriter();try {Class.forName("com.mysql.jdbc.Driver");Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");PreparedStatement ps = con.prepareStatement("select name from auto where name like '%"+sname+"%'");ResultSet rs = ps.executeQuery();while(rs.next()){pw.print("<li>"+rs.getString("name")+"</li>");}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}}


1.輸入一個字母a,自動觸發資料庫檢索,然後將結果返回到頁面:


2.滑鼠懸浮效果:


3.點擊選中結果:



搜尋引擎輸入自動補全

GOOGLE的自動補全你是拿不了的!!!要麼你就掛他的搜尋條!!要不你就自己寫一個自動補全的!可以用Ajax來實現!
 
ASP 搜尋提示(自動補全)

你是只免重新整理功能吧
那你最好換個語言用ASP。NET吧
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.