JavaScript實現郵箱地址自動匹配功能代碼_javascript技巧

來源:互聯網
上載者:User

自動匹配技術:簡單的來說就是“根據使用者輸入的資訊來提示一些相似項供使用者選擇”。具有很廣泛的應用,比如我們最常用的百度,當輸入一些搜尋內容後會自動匹配很多相關資訊;再比如我們最常用的IME,都是使用這種技術,當然這些都比較難了。下面這個例子是比較簡單的我們常用郵箱的匹配。代碼如下:

1.css代碼

  #match_email  {    margin-left:48px;    overflow:auto;     display:none;    width:200px;    border:1px solid #aaa;    background:#fff;    max-height:100px;    line-height:20px;  }  #match_email div  {    text-decoration:none;    color:#000;    width:200px;  }  #match_email div:hover  {    background:#aaa;    }  input  {    height:20px;      width:200px;  }

在css中將overflow設為auto以及將max-height設為100px表示,在該div高度超多100px就是自動產生捲軸。

2.html代碼

<div>  郵箱:<input type="text" name="email" id="email" autocomplete="off" onkeyup="match_mail(this.value)"/>  <div id="match_email"></div></div>

onkeyup時間表示只要手指離開按鈕就會觸發

3.js代碼

<script>  //mailBoxs裡儲存用來匹配的串  var mailBoxs = "@163.com @126.com @129.com"  mailBoxs += " @qq.com @vip.qq.com @foxmail.com @live.cn @hotmail.com @sina.com @sina.cn @vip.sina.com";  var matchmail = document.getElementById("match_email");  var email = document.getElementById("email");  function match_mail(keyword)  {    matchmail.innerHTML = "";    matchmail.style.display = "none";    if (!keyword)      return;    if (!keyword.match(/^[\w\.\-]+@\w*[\.]?\w*/))        return;    keyword = keyword.match(/@\w*[\.]?\w*/);    var matchs = mailBoxs.match(new RegExp(keyword+"[^ ]* ","gm"));    if (matchs)    {      matchs = matchs.join("").replace(/ $/,"").split(" ");      matchmail.style.display = "block";      for (var i = 0; i < matchs.length; i++)      {        matchmail.innerHTML += '<div>'+matchs[i]+'</div>';       }      }  }  //點擊除了匹配框之外的任何地方,匹配框消失  document.onclick = function(e)  {    var target = e.target;    if (target.id != "matchmail")      matchmail.style.display = "none";    }  //將匹配框上滑鼠所點的字元放入輸入框  matchmail.onclick = function(e)  {    var target = e.target;    email.value = email.value.replace(/@.*/,target.innerHTML);  }</script>

在js中好幾處都用到了Regex:
(1)keyword = keyword.match(/@\w*[\.]?\w*/);只擷取@後面的內容,包括@;
(2)var matchs = mailBoxs.match(new RegExp(keyword+"[^ ]* ","gm"));進行匹配,把mailBoxs中和keyword匹配的存入matchs中,[^ ]* 指遇到空格不匹配,參數”gm”中'g'指進行全域匹配,'m'指多行匹配;
(3)matchs = matchs.join("").replace(/ $/,"").split(" ");字串的結尾用空格匹配,$表示字串的結尾。

在兩個匿名函數中,e是在滑鼠點擊事件發生時系統自動產生的·,e.target是獲得滑鼠所點的當前對象。

最終效果如圖:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.