用jquery实现自动填充功能
现在公司有一个项目需要实现一个功能 当点下拉框时动态加载后台数据。因为之前使用过jquery,所以很快想到使用jquery实现这一功能,但后来发现公司所做的项目界面全部是通过配置文件生成的,每一个文本域的CSS都不一样,在界面很难统一一个CSS样式去动态生成一个下来列表与原来的文本域宽度以及坐标相匹配,总之,使用这种方式html、css、javascript代码耦合度太高了,不适合于全局使用。当然通过javascript代码也能实现下拉列表的坐标定位,但是这样做又过于复杂,不可取。
用Jquery实现的自动填充代码如下,网上也有实现此功能的插件,可以用用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>jQuery实现自动提示的文本框</title>
<style>
<!--
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px; padding:0px; margin:5px;
}
form{padding:0px; margin:0px;}
input{
/* 用户输入框的样式 */
font-family:Arial, Helvetica, sans-serif;
font-size:12px; border:1px solid #000000;
width:200px; padding:1px; margin:0px;
}
#popup{
/* 提示框div块的样式 */
position:absolute; width:202px;
color:#004a7e; font-size:12px;
font-family:Arial, Helvetica, sans-serif;
left:41px; top:25px;
}
#popup.show{
/* 显示提示框的边框 */
border:1px solid #004a7e;
}
/* 提示框的样式风格 */
ul{
list-style:none;
margin:0px; padding:0px;
color:#004a7e;
}
li.mouseOver{
background-color:#004a7e;
color:#FFFFFF;
}
-->
</style>
<script language="javascript" src="jquery.min.js"></script>
<script language="javascript">
var oInputField; //考虑到很多函数中都要使用
var oPopDiv; //因此采用全局变量的形式
var oColorsUl;
function initVars(){
//初始化变量
oInputField = $("#colors");
oPopDiv = $("#popup");
oColorsUl = $("#colors_ul");
}
function clearColors(){
//清除提示内容
oColorsUl.empty();
oPopDiv.removeClass("show");
}
function setColors(the_colors){
//显示提示框,传入的参数即为匹配出来的结果组成的数组
clearColors(); //每输入一个字母就先清除原先的提示,再继续
oPopDiv.addClass("show");
for(var i=0;i<the_colors .length;i++)
//将匹配的提示结果逐一显示给用户
oColorsUl.append($("<li>"+the_colors[i]+""));
oColorsUl.find("li").click(function(){
oInputField.val($(this).text());
clearColors();
}).hover(
function(){$(this).addClass("mouseOver");},
function(){$(this).removeClass("mouseOver");}
);
}
function findColors(){
initVars(); //初始化变量
if(oInputField.val().length > 0){
//获取异步数据
$.get("14-10.aspx",{sColor:oInputField.val()},
function(data){
var aResult = new Array();
if(data.length > 0){
aResult = data.split(",");
setColors(aResult); //显示服务器结果
}
else
clearColors();
});
}
else
clearColors(); //无输入时清除提示框(例如用户按del键)
}
</the_colors></script>
</head>
<body>
<form method="post" name="myForm1">
Color: <input type="text" name="colors" id="colors" onkeyup="findColors();" />
</form>
<div id="popup">
<ul id="colors_ul"></ul>
</div>
</body>
</html> |
Recent Comments