【转载】使用jquery做类似搜索引擎效果

当用户输入电话号码的时候,会自动出现提示。类似于google搜索引擎效果,

之前用javascript写过一个,但是目前使用jquery更为简单。

 1 var line = 0;
2 var sendType;
3 function del(){
4 if($("#newDiv")){
5 $("#newDiv").remove();
6 line = 0;
7 }
8 }
9 $(document).ready(function(){
10 //文本框失去焦点时层消失
11 $(document.body).click(function(){
12 del();
13 });
14 $(document).keydown(function(){
15 // 38 上 40下 13 回车
16 if($("#newDiv")){
17 if(event.keyCode == 40){
18 $("table tbody tr").eq(line)
19 .css("backgroundColor", "blue")
20 .css("color", "white");
21 $("table tbody tr").eq(line < 0 ? 0 : line - 1)
22 .css("backgroundColor", "white")
23 .css("color", "black");
24 line = (line == $("table tbody tr").length ? 0 : line + 1);
25 }else if(event.keyCode == 38){
26 line = (line == 0 ? $("table tbody tr").length : line - 1);
27 $("table tbody tr").eq(line)
28 .css("backgroundColor", "blue")
29 .css("color", "white");
30 $("table tbody tr").eq(line > $("table tbody tr").length ? 0 : line + 1)
31 .css("backgroundColor", "white")
32 .css("color", "black");
33 }else if(event.keyCode == 13){
34 $("#phoneno").val($("table tbody tr").eq(line - 1).find("td").eq(0).html());
35 del();
36 }
37 }
38 });
39
40 //只要id为phoneno的文本框变化,就调用function()
41
42 $("#phoneno").bind("propertychange", function(){
43 del();
44 var top = $("#phoneno").offset().top;
45 var left = $("#phoneno").offset().left;
46 var newDiv = $("<div/>").width($("#phoneno").width() + 6)
47 .css("position", "absolute")
48 .css("backgroundColor", "white")
49 .css("left", left)
50 .css("top", top + $("#phoneno").height() + 6)
51 .css("border", "1px solid blue")
52 .attr("id", "newDiv");
53
54 var table = $("<table width='100%'/>")
55 .attr("cellpadding", "0")
56 .attr("cellspacing", "0");
57 //$.get("xmlPhoneno", {phoneno: $("#phoneno").val()},function(xml){
58 $.get("phoneNoInfo.xml", {PhoneNumber: $("#phoneno").val()},function(xml){
59
60 //这里调用了后台的xmlController来执行发挥xml。以下为解析xml
61 $(xml).find("phones phone").each(function(){
62 var phoneno = $(this).attr("phoneno");
63 var sname = $(this).attr("sname");
64 var tr = $("<tr/>").css("cursor", "pointer").mouseout(function(){
65 $(this).css("backgroundColor", "white").css("color", "black");
66 }).mouseover(function(){
67 $(this).css("backgroundColor", "blue").css("color", "white");
68 }).click(function(){
69 $("#phoneno").val($(this).find("td").eq(0).html());
70 del();
71 });
72 var td1 = $("<td/>").html(phoneno).css("fontSize", "12px")
73 .css("margin", "5 5 5 5");
74 var td2 = $("<td/>").html(sname)
75 .attr("align", "right").css("fontSize", "12px")
76 .css("color", "green").css("margin", "5 5 5 5");
77
78 tr.append(td1).append(td2);
79 table.append(tr);
80 newDiv.append(table);
81 });
82 });
83 $(document.body).append(newDiv);
84 if($("#phoneno").val() == ""){
85 $("#newDiv").remove();
86 }
87 });
88 }

转载于:https://my.oschina.net/weisenz/blog/200644

猜你喜欢

转载自blog.csdn.net/weixin_34392843/article/details/91920865