我在javascript中实现了一个自动完成列表,这样如果用户输入“a”,则所有以“a”开头的名称都会显示在下拉菜单中。现在我想根据下拉菜单中的用户输入使文本变为粗体。因此,如果用户输入“ab”,则字母“ab”应在包含“约”字样的下拉菜单中显示为粗体。
这是我的JS代码的一部分,我正在显示名称:
document.getElementById('dropmenu').style.visibility='visible';
var element = document.createElement("div");
var namecontainer = document.createElement("div");
namecontainer.setAttribute('id', "name" + div_id);
namecontainer.className = "namecontainerclass";
element.setAttribute('id', "div" + div_id);
element.className = "elementclass";
var text = document.createTextNode(myArray[i].name);
element.appendChild(text);
document.getElementById('dropmenu').appendChild(namecontainer);
document.getElementById("name" + div_id).appendChild(element);
var img=document.createElement("img");
img.setAttribute("src", myArray[i].image);
img.setAttribute("width", 25);
img.setAttribute("height", 25);
namecontainer.appendChild(img);
答案 0 :(得分:0)
这是我想到的事情。您想要根据名称(myArray [i] .name)检查用户输入,此时创建一些textnodes
(如果匹配,则创建element
),并将它们附加到容器元素(在这种情况下为div
)。我没有测试它,但它显示了如何在不使用任何javascript框架的情况下处理这种高亮显示有点伪代码。
// searchString is the string entered by the user...
// split by the searchString, but group the selection so the matches
// also get added to the result array.
var match = new RegExp('\\('+ searchString +')\\',"gi");
var textParts = myArray[i].name.split(match);
var nodes = [];
var element = document.createElement("div");
// only create elements for names that actually match.
// if there is only one match, there wasn't a match by the split
if (textParts.length > 1){
for(i = 0; i < textParts.length; i++){
if (textParts[i] == searchString) {
nodes[i] = document.createElement("em");
nodes[i].createTextNode(searchString);
} else {
nodes[i] = document.createTextNode(textparts[i]));
}
element.appendChild(nodes[i]);
}
}