http://jsfiddle.net/rh48cgrj/3/
這裏有一個小提琴。我將選項值/文本放入javascript對象中的key:value對中。注意:密鑰是一個索引號和值是選項值屬性和文本。這樣可以更輕鬆地搜索他們的文字。
var i = 0;
var selectItems = {}
$('#tagList option').each(function() {
var listvalue = $(this).val();
var listtext = $(this).text();
selectItems[i] = listvalue + " " + listtext + ",";
i++;
});
然後我將它們分成包含值和文本的行。
count = i;
for(i=0; i < count;i++) {
var blockoftext = blockoftext + " " + selectItems[i].toLowerCase() + ",";
}
我再設置一個搜索功能,將搜索那些行,看看是否有返回的比賽,如果他們做的結果輸出到搜索框下方的一個div。
var texttosplit = blockoftext.split(",");
var searchresults;
for(i=0; i < texttosplit.length; i++) {
(texttosplit[i].indexOf(searchvalue.toLowerCase()) != -1) ?
(searchresults = texttosplit[i] + "<br>") : false;
$("#searched").html(searchresults);
}
在小提琴中有上述所有的例子。
編輯:下面是循環的註釋代碼,以檢查搜索文本是否在每個操作請求的數據列表中。
for (i = 0; i < texttosplit.length; i++) {
//The above loops through our array of class values and titles
(texttosplit[i].indexOf(searchvalue.toLowerCase()) != -1) ?
// The above determines if our search text is in class title using a ternary operator
// our array of class values and titles is lowercase so we make
//sure our search text is lowercase as well
// if we find a match between the search text and the class title/values perform the following:
(searchresults = texttosplit[i].replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
})
// The above replaces the first char of every word with an uppercase char
.replace("Csci", "CSCI") + "<br>",
// The above finds Csci and changes it to CSCI since all THOSE letters should be uppercase
prevtext = $("#searched").html(),
//get current text of element with id "searched" and place it in prevtext
$("#searched").html(prevtext + searchresults))
//append "searched" by adding it's current text with the new searchresults
:
//if search text is not in the class title return false
false;
}
非常感謝!但是,有2個問題。 1)是否有可能在
http://jsfiddle.net/Lf09ydu7/7/我清理了一下代碼。當您搜索時只顯示最後一個元素是我的錯誤,而不是附加到搜索結果div我覆蓋它,所以我爲你解決了這個問題。此外,我還修復了代碼,以便在返回搜索結果時,所有單詞都以大寫字母開頭。 – zfrisch
@BlazeBiker你對這個問題還有其他疑問嗎? :D 否則,如果我徹底解答了您的問題,請接受它以幫助其他人在網站上找到它! – zfrisch