jQuery 郵箱輸入字尾自動補全

admin發表於2019-01-22

分享一段程式碼例項,它實現了輸入郵箱字尾自動補全效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
function inputList(input, list) {
  var mailBox = [
    "@qq.com",
    "@sina.com",
    "@163.com",
    "@126.com",
    "@yahoo.com.cn",
    "@gmail.com",
    "@sohu.com"
  ];
 
  input.bind('input propertychange', function() {
    var key = input.val();
    if (key.indexOf("@") != -1) {
      key = key.slice(0, key.indexOf("@"));
    }
    var mailBoxLen = mailBox.length;
    var html = "";
    for (var index = 0; index < mailBoxLen; index++) {
      html += '<option value="' + key + mailBox[index] + '"></option>';
    }
    list.html(html);
  });
 
}
$(document).ready(function() {
  inputList($("input"), $("#input_list"));
})
</script>
</head>
<body>
<input type="text" list="input_list" name="text" placeholder="請輸入郵箱" />
<datalist id="input_list"></datalist>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).function inputList(input, list) {},第一個引數是jquery獲取的文字框物件,第二個引數是與第一個引數關聯的datalist物件。

(2).var mailBox = [

  "@qq.com",

  "@sina.com",

  "@163.com",

  "@126.com",

  "@yahoo.com.cn",

  "@gmail.com",

  "@sohu.com"

],儲存郵箱字尾的陣列。

(3).input.bind('input propertychange', function() {}),為文字框註冊propertychange事件處理函式;文字框內容發生變化就會觸發此事件。

(4).var key = input.val(),獲取文字框的值。

(5). if (key.indexOf("@") != -1) {

  key = key.slice(0, key.indexOf("@"));

},如果輸入的字串有@符號,那麼就在刪除這個@,否則的話再加上預設郵箱字尾,就會出現兩個@符號。

(6).var mailBoxLen = mailBox.length,將陣列的長度存入指定變數。

(7).var html = "",清空內容,防止前後內容疊加。

(8).for (var index = 0; index < mailBoxLen; index++) {

  html += '<option value="' + key + mailBox[index] + '"></option>';

},生成預設的郵箱字尾選項。

(9).list.html(html),將郵箱字尾寫入。

二.相關閱讀:

(1).indexOf()可以參閱JavaScript indexOf()一章節。

(2).slice()可以參閱JavaScript slice()一章節。

(3).html()可以參閱jQuery html()方法一章節。

(4).datalist可以參閱HTML5 <datalist>標籤一章節。

相關文章