JS实现联想、自动补齐国家或地区名称的功能

1.JS部分

function autocomplete(inp, arr) {
 /*函数主要有两个参数:文本框元素和自动补齐的完整数据*/
 var currentFocus;
 /* 监听 - 在写入时触发 */
 inp.addEventListener("input", function(e) {
   var a, b, i, val = this.value;
   /*关闭已经打开的自动完成值列表*/
   closeAllLists();
   if (!val) { return false;}
   currentFocus = -1;
   /*创建列表*/
   a = document.createElement("DIV");
   a.setAttribute("id", this.id + "autocomplete-list");
   a.setAttribute("class", "autocomplete-items");
   /*添加 DIV 元素*/
   this.parentNode.appendChild(a);
   /*循环数组...*/
   for (i = 0; i < arr.length; i++) {
    /*检查选项是否以与文本字段值相同的字母开头*/
    if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
     /*为匹配元素创建 DIV*/
     b = document.createElement("DIV");
     /*使匹配字母变粗体*/
     b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
     b.innerHTML += arr[i].substr(val.length);
     /*insert a input field that will hold the current array item's value:*/
     b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
     /*execute a function when someone clicks on the item value (DIV element):*/
     b.addEventListener("click", function(e) {
       /*insert the value for the autocomplete text field:*/
       inp.value = this.getElementsByTagName("input")[0].value;
       /*close the list of autocompleted values,
       (or any other open lists of autocompleted values:*/
       closeAllLists();
     });
     a.appendChild(b);
    }
   }
 });
 /*execute a function presses a key on the keyboard:*/
 inp.addEventListener("keydown", function(e) {
   var x = document.getElementById(this.id + "autocomplete-list");
   if (x) x = x.getElementsByTagName("div");
   if (e.keyCode == 40) {
    /*If the arrow DOWN key is pressed,
    increase the currentFocus variable:*/
    currentFocus++;
    /*and and make the current item more visible:*/
    addActive(x);
   } else if (e.keyCode == 38) { //up
    /*If the arrow UP key is pressed,
    decrease the currentFocus variable:*/
    currentFocus--;
    /*and and make the current item more visible:*/
    addActive(x);
   } else if (e.keyCode == 13) {
    /*If the ENTER key is pressed, prevent the form from being submitted,*/
    e.preventDefault();
    if (currentFocus > -1) {
     /*and simulate a click on the "active" item:*/
     if (x) x[currentFocus].click();
    }
   }
 });
 function addActive(x) {
  /*a function to classify an item as "active":*/
  if (!x) return false;
  /*start by removing the "active" class on all items:*/
  removeActive(x);
  if (currentFocus >= x.length) currentFocus = 0;
  if (currentFocus < 0) currentFocus = (x.length - 1);
  /*add class "autocomplete-active":*/
  x[currentFocus].classList.add("autocomplete-active");
 }
 function removeActive(x) {
  /*a function to remove the "active" class from all autocomplete items:*/
  for (var i = 0; i < x.length; i++) {
   x[i].classList.remove("autocomplete-active");
  }
 }
 function closeAllLists(elmnt) {
  /*close all autocomplete lists in the document,
  except the one passed as an argument:*/
  var x = document.getElementsByClassName("autocomplete-items");
  for (var i = 0; i < x.length; i++) {
   if (elmnt != x[i] && elmnt != inp) {
    x[i].parentNode.removeChild(x[i]);
   }
  }
 }
 /*execute a function when someone clicks in the document:*/
 document.addEventListener("click", function (e) {
   closeAllLists(e.target);
   });
}

/*数组 - 包含所有国家或地区名*/
var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong China","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau China","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan China","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];

/*传递参数*/
autocomplete(document.getElementById("myInput"), countries);

2.CSS部分

* { box-sizing: border-box; }
body {
 font: 16px Arial;
}
.autocomplete {
 /*the container must be positioned relative:*/
 position: relative;
 display: inline-block;
}
input {
 border: 1px solid transparent;
 background-color: #f1f1f1;
 padding: 10px;
 font-size: 16px;
}
input[type=text] {
 background-color: #f1f1f1;
 width: 100%;
}
input[type=submit] {
 background-color: DodgerBlue;
 color: #fff;
}
.autocomplete-items {
 position: absolute;
 border: 1px solid #d4d4d4;
 border-bottom: none;
 border-top: none;
 z-index: 99;
 /*position the autocomplete items to be the same width as the container:*/
 top: 100%;
 left: 0;
 right: 0;
}
.autocomplete-items div {
 padding: 10px;
 cursor: pointer;
 background-color: #fff;
 border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
 /*when hovering an item:*/
 background-color: #e9e9e9;
}
.autocomplete-active {
 /*when navigating through the items using the arrow keys:*/
 background-color: DodgerBlue !important;
 color: #ffffff;
}

3.HTML部分

<!-- 关闭自带的自动补全功能 -->
<form autocomplete="off" action="/action_page.php">
 <div class="autocomplete" style="width:300px;">
  <input id="myInput" type="text" name="myCountry" placeholder="输入国家或地区英文名...">
 </div>
 <input type="submit">
</form>

4.效果图

以上就是JS实现联想、自动补齐国家或地区名称的功能的详细内容,更多关于JS 联想、自动补齐功能的资料请关注我们其它相关文章!

(0)

相关推荐

  • Json实现传值到后台代码实例

    1.定义一个键值对对象 function ObjData(key,value){ this.Key=key; this.Value=value; } 2.在点击表单的提交buttom的方法中: var list=document.getElementById("myForm").getElementsByTagName("input");//查询form下的所有input标签 var array=[]; //定义一个对象数据 存放每一个input的键值对(input

  • JS制作简易计算器的实例代码

    做一个简易计算器,效果图片 c表示清空,为一个空字符串 +/-表示该值为正还是负 %表示当前值/100 ←表示退格,往前删除一个值 eval 函数是能够计算出字符串表达式或者语句的结果,把结果求出来. 代码如下 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"

  • Json字符串转Java对象和List代码实例

    对象POJO和JSON互转 public class JsonUtil { /** * JSON 转 POJO */ public static <T> T getObject(String pojo, Class<T> tclass) { try { return JSONObject.parseObject(pojo, tclass); } catch (Exception e) { log.error(tclass + "转 JSON 失败"); } re

  • JavaScript多种图形实现代码实例

    1.小星星 设有如下的曲线参数方程: N=5 x = r*sin(nθ)*cos(θ) y = r*sin(nθ)*sin(θ) (0≤θ≤2π) 用循环依次取θ值为0~2π(每次增量为π/64),计算出X和Y,在canvas画布中将坐标点(X,Y)用线连起来,可绘制出一个一个5瓣花卉图案. 编写如下的HTML代码. <!DOCTYPE html> <head> <title>小星星</title> <script type="text/ja

  • 实例讲解JavaScript 计时事件

    JavaScript 计时事件 通过使用 JavaScript,我们有能力做到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行.我们称之为计时事件. 在 JavaScritp 中使用计时事件是很容易的,两个关键方法是: setInterval() - 间隔指定的毫秒数不停地执行指定的代码. setTimeout() - 在指定的毫秒数后执行指定代码. 注意: setInterval() 和 setTimeout() 是 HTML DOM Window对象的两个方法. setInt

  • JS简易计算器实例讲解

    本文实例为大家分享了JS实现简易计算器的具体代码,供大家参考,具体内容如下 简易计算器: 1)选择需要运算的类型,输入对应的数字 2)输入需要参与运算的数字 3)输入"计算"二字,进行运算后,显示运算结果及运算表达式 <script type="text/javascript"> // 加法运算 function plus(arrPlus){ var sum = 0; for(var i = 0 ; i < arrPlus.length ; i++

  • JS猜数字游戏实例讲解

    本文实例为大家分享了JS实现猜数字游戏的具体代码,供大家参考,具体内容如下 猜数字游戏: 1)利用JS的Math内置对象,实现在1-50内选取一个整数随机数作为游戏答案 2)输入数字进行判断,共有10次输入机会 3)若大于答案数字,则提示猜大了,若小于答案数字,则提示猜小了 4)直至10次机会用完或者猜对答案了,则结束游戏 <script type="text/javascript"> // 猜数字案例 function guessTip(min, max) { min =

  • 通过实例了解JS执行上下文运行原理

    壹 ❀ 引 我们都知道,JS代码的执行顺序总是与代码先后顺序有所差异,当先抛开异步问题你会发现就算是同步代码,它的执行也与你的预期不一致,比如: function f1() { console.log('听风是风'); }; f1(); //echo function f1() { console.log('echo'); }; f1(); //echo 按照代码书写顺序,应该先输出 听风是风,再输出 echo才对,很遗憾,两次输出均为 echo:如果我们将上述代码中的函数声明改为函数表达式,结

  • JS原型对象操作实例分析

    本文实例讲述了JS原型对象操作.分享给大家供大家参考,具体如下: 万物皆对象,函数也同样是对象,是特殊的函数对象 function fn() {} let a = new fn(); let b = new Function() console.log(typeof a); // object console.log(typeof b); // function 打开浏览器,输入fn,会发现fn有一个prototype(原型)属性,这个属性是一个指针,指向原型对象,这个对象包括了特定类型所有共享

  • JS实现联想、自动补齐国家或地区名称的功能

    1.JS部分 function autocomplete(inp, arr) { /*函数主要有两个参数:文本框元素和自动补齐的完整数据*/ var currentFocus; /* 监听 - 在写入时触发 */ inp.addEventListener("input", function(e) { var a, b, i, val = this.value; /*关闭已经打开的自动完成值列表*/ closeAllLists(); if (!val) { return false;}

  • js实现前面自动补全位数的方法

    例如我们希望输出的数字长度是固定的,假设为10,如果数字为123,则输出0000000123,不够位数就在之前补足0,这里提供了四种不同的方式实现JS代码给数字补0 的操作 第一种 function PrefixInteger(num, length) { return (num/Math.pow(10,length)).toFixed(length).substr(2); } 第二种 function PrefixInteger(num, length) { return ( "0000000

  • 使用Bootstrap typeahead插件实现搜索框自动补全的方法

    这就是贴代码的坏处之一:搜索框快被网友玩儿坏了!!!有故意输入空格的,有输入or 1=1的,有alert的,有html乱入的.......而且好像还在玩儿,随他们去吧,只要开心就好. 在项目中,经常会用到输入框的自动补全功能,就像百度.淘宝等搜索框一样:当用户输入首字母.关键词时,后台会迅速将与此相关的条目返回并显示到前台,以便用户选择,提升用户体验.当然本项目的补全功能和这些大厂的技术是没有可比性的,但用于站内搜索也是绰绰有余了. 接触到的自动补全插件主要有两个:autocomplete和ty

  • asp.net+ajax+sqlserver自动补全功能实现解析

    代码下载 说明:数据库连接字符串在web.config文件中,为方便运行使用的是官方的Northwind数据库. 参考(向其作者致敬): ² http://www.loveweb8.com/plus/demo.php?aid=57这个例子是html源码.利用jquery.autocomplete插件利用js实现了自动补全功能.由于我的需要是结合sqlserver数据库表实现自动补全功能.就下来就是将数据库表转为js数组,自然而然就想到了ajax. ² Asp.NetAjax的两种基本开发模式这篇

  • jquery css实现邮箱自动补全

    今天在公司做一个电子商务网站的注册会员时,要求用户在电子邮箱文本框中输入时,给与热点提示常用的电子邮箱,帮助用户选择,提高体验效果.下面是用Jquery+css实现的邮箱自动补全,供大家参考和学习. HTML代码:emailAutoComple.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>邮箱自动补全&l

  • Ajax实现关键字联想和自动补全功能及遇到坑

    目录 遇到的小坑 代码实现 前端代码 后端代码 用到的实体类 自己封装的jdbc工具类 数据库表: 效果展示: 遇到的小坑 回调函数相对window.onload的摆放位置 给回调函数addData传数据时,如何操作才能将数据传进去 代码实现 前端代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax实现关键

  • 搜索历史基本原理实现即时自动补全联想搜索技巧

    目录 实现搜索历史-[即时自动补全&联想搜索] 如何实现基于个人搜索历史的联想推荐 架构图 词汇表实现 实现原理 新增关键字操作 删除关键字操作 查询推荐列表操作 实现搜索历史-[即时自动补全&联想搜索] 无论是新闻.内容.还是电商平台,联想输入已经成为搜索功能的标配,早已不是什么新鲜事物.我们随便打开一个搜索引擎或者是电商平台,当我们在输入框输入拼音或者文字时就会看到输入框下方弹出有意义的搜索建议,提示我们是不是想要输入“以下”内容,帮助我们补齐输入或是修正错误的输入,优化我们的搜索体验

  • PHP实现HTML标签自动补全代码

    一般情况下先用PHP的 strip_tags 函数去掉所有html标签,再去掉空格等,然后再用substr或者自己实现的cn_substr函数来实现截取.因为如果不先去掉html标签,直接截取出来的字符串就会有没有闭合的标签出现,有时甚至会截取在标签上面比如 复制代码 代码如下: </di ... 今天遇到一个内容翻页截取问题: 正文是用富文本编辑器写入的,编辑器上有个分页按钮,点击之后就往当前光标位置插入一个蓝色的 复制代码 代码如下: <hr /> 横线.然后php直接存入数据库.显

  • easyui-combobox 实现简单的自动补全功能示例

    前台:  Html页面 <input id="clsydw" name="clsydw" class="easyui-combobox" data-options="" /> JS //自动补全功能 $("#clsydw").combobox({ valueField:'syr', textField:'syr', panelWidth:200, panelHeight:'auto', onCh

  • BootStrap Typeahead自动补全插件实例代码

    关键代码如下所示: $('#Sale').typeahead({ ajax: { url: '@Url.Action("../Contract/GetSale")', //timeout: 300, method: 'post', triggerLength: 1, loadingClass: null, preProcess: function (result) { return result; } }, display: "Value", val: "

随机推荐