2012-10-03 42 views
0

我已經在javascript中實現了一個自動完成列表,因此如果用戶鍵入'a',則所有以'a'開頭的名稱都將顯示在下拉菜單中。現在我想在下拉菜單中根據用戶輸入設置粗體文字。因此,如果用戶鍵入'ab',字母'ab'應該在包含單詞about的下拉菜單中顯示爲粗體。在javascript中以文本粗體顯示用戶類型

這裏是我的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); 
+2

爲什麼你重新創建輪子,而不是使用腳本已經這樣做了?另外,我們無法幫助您修復代碼,而不會看到您寫的任何內容。 – epascarello

+0

我正在學習Javascript,所以這只是一個示例函數,可以幫助我理解這些東西。 –

回答

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]); 
    } 

} 
相關問題