我已多次发布关于我的问题,但我把整个代码放在了小提琴上。我只是试图通过变量db搜索任何匹配。我知道有更简单的方法可以做到这一点,但这是一个学校项目。
以下是链接:jsfiddle.net/PByE2 /#& togetherjs = N35plzbb5L
答案 0 :(得分:0)
在jsFiddle中,我们想出了这个结果
(function() {
var form = document.getElementById("searchwrap"),
searchField = document.getElementById("search"),
results = document.getElementById("results");
function validateQuery(query) {
// display error message for less than 3 characters
if (query.trim().length < 3) {
throw new Error("Your query must be at least 3 characters long");
}
}
function queryConcepts(query) {
var parts, idx, re;
for (var i=0; i<db.length; i++) {
// split the db row on the "|" character
parts = db[i].split("|");
// create an index of the data; e.g.,
// {topic: "Error Types", url: "http://..."}
idx = {topic: parts[0], url: parts[1]};
// create a case-insensitive RegExp to test if our query matches the topic
re = new RegExp(query, "i");
// perform the check; render the result if we have a match
if (re.test(idx.topic)) {
renderResult(idx);
}
}
}
function renderResult(idx) {
// build P and A tag
var p = document.createElement("p"),
a = document.createElement("a");
// setup A
a.href = idx.url;
a.innerHTML = idx.topic;
// attach A to P
p.appendChild(a);
// attach result to output
results.appendChild(p);
}
function clearResults() {
// clear all result contents
results.innerHTML = "";
}
function checkForEmptyResult() {
// search for results
var r = results.getElementsByTagName("p");
// if there are no results, display the "empty result" message
if (r.length === 0) {
renderEmptyResult();
}
}
function renderEmptyResult() {
// display no results found
var p = document.createElement("p");
p.innerHTML = "No results found.";
// provide a recommended search
var p2 = document.createElement("p");
p2.appendChild(document.createTextNode("Try searching for "));
// with a linked search term
var a = document.createElement("a");
a.href="#query";
a.innerHTML = "script";
a.addEventListener("click", function(event) {
searchField.value = "script";
event.preventDefault();
});
p2.appendChild(a);
// attach text to results section
results.appendChild(p);
results.appendChild(p2);
}
form.addEventListener("submit", function(event) {
try {
clearResults();
validateQuery(searchField.value);
queryConcepts(searchField.value);
checkForEmptyResult();
}
catch (err) {
alert(err);
}
// don't attempt to submit the form data
event.preventDefault();
});
})();