我正在尝试实现文本框自动完成,这是代码
HTML
<div class="sug">
<input type="text" id="auto" onkeyup="display(event)" onblur="hide()" autocomplete="off"/>
<div class="suggestion" id="suggestion">
</div>
</div>
CSS
.suggestion {
border: solid 2px black;
}
.sug > .suggestion {
display: none;
}
.sug > .suggestion, #auto {
width: 100px;
}
JavaScript
var array = new Array();
array.push("heena");
array.push("bhawin");
array.push("aruna");
array.push("mahesh");
array.push("anshul");
array.push("jagruti");
array.push("neha");
array.push("sherry");
array.push("sonali");
var data;
var id;//for providing id to each div
function display(e) {
if (e.keyCode == 38 || e.keyCode == 40) {
selectit(e);
}
data = "";
id = 0;
var state = $('#auto').val();
if (state == "")//value empty
{
$('.suggestion').css({display: "none"});
}
else {
for (var i = 0; i < array.length; i++) {
var key = 0;
for (j = 0; j < state.length; j++) {
//for the matching of the array element with the text in the textbox
if (array[i][j] == state[j]) {
key++;
}
}
//putting the matched array element in a div
if (key == state.length) {
//the whole array will be copied with the bold values inserted
var bolde = "";
for (var k = 0; k < key; k++) {
bolde += "<b>" + array[i][k] + "</b>";
}
for (var l = key; l < array[i].length; l++) {
bolde += array[i][l];
}
id++;
data += "<div id='" + id + "'>" + bolde + "</div>";
}
}
$('.suggestion').html(data);
$('.suggestion').css({display: "block"});
if (data == "") {
$('.suggestion').css({display: "none"});
}
}
}
function hide() {
$('#suggestion').css({display: "none"});
;
}
function selectit(e) {
var child = document.getElementById("suggestion").childNodes;
for (var i = 0; i < child.length; i++) {
if (child[i].id == "1") {
child[i].style.color = "red"; //here is the problem in the code
}
}
}
在代码中,我想在按下按键时将第一个建议颜色设为红色,但颜色未显示
最后一条评论是问题所在的区域。