javascript - 尝试在 Javascript (Twine) 中创建一个简单的基于关键字的搜索栏
问题描述
我正在尝试使用 Javascript 在 Twine 故事中创建一个简单的基于关键字的搜索功能。使用本指南我有一些功能,但我正在尝试稍微修改它。我希望搜索输出所有匹配项,而不仅仅是最高匹配项,或者至少是前 5 个最高匹配项。谁能帮我这个?不幸的是,我对 Javascript 不是很熟悉,因此试图弄清楚要更改什么,然后将其更改为什么非常困难。
window.SearchTerm = window.SearchTerm || function (h, descr, kw) {
'use strict';
if (this instanceof SearchTerm) {
this.handle = h;
this.description = descr;
this.keywords = kw;
} else {
return new SearchTerm(h, descr, kw);
}
};
SearchTerm.add = function (h, descr, kw) {
termList.push(new SearchTerm(h, descr, kw));
};
SearchTerm.prototype = {
compare : function (stringArray) {
var term = this;
var matches = (function () {
var ret = 0;
stringArray.forEach( function (str) {
if (term.keywords.includes(str)) {
ret++;
}
});
return ret;
}());
return matches;
},
constructor : window.SearchTerm
};
$(document).on('change', 'input[name=search-box]', function (e) {
var string = $(this).val(),
matches = [], i, n = -1, highest = 0, content;
string = string.replace(/[^A-Za-z0-9\s]/, ' ');
string = string.replace(/[\s\s+]/, ' ');
string = string.trim();
string = string.split(' ');
termList.forEach( function (term) {
matches.push(term.compare(string));
});
for (i = 0; i < matches.length; i++) {
if (matches[i] > n) {
n = matches[i];
highest = i;
}
}
if (n <= 0) {
content = '';
} else {
content = termList[highest].handle + ': ' + termList[highest].description;
}
$('#output')
.empty()
.append(content);
});
// add your search terms here...
SearchTerm.add('Test', '#000', ['test', 'testing']);
SearchTerm.add('Test', '#001', ['test', 'testing']);
SearchTerm.add('Test', '#002', ['test', 'testing']);
// etc.
解决方案
推荐阅读
- android - Android Q Api 29 - 如何从“存储访问框架”获取存储(SD 卡)的大小(总或可用)
- spring-boot - Oauth2:Spring Boot 2:设计:不同的身份验证服务器和资源服务器 - 在哪里存储所有用户信息?
- postman - 在 Postman 中将字符串值与 .json 数据进行 API 测试比较
- python - 在线性规划中添加到约束的变量的条件语句
- php - 如何从 UserInfo 端点获取职位和电话号码
- go - 读取函数完成后未更新 Go rot13Reader 缓冲区之旅
- php - 致命错误:未捕获的 Google_Service_Exception:{“错误”:{“代码”:400,“消息”:“收到无效的 JSON 有效负载。未知名称\“名称\”
- javascript - 我要构建一个“使用 jQuery 的动态琐事游戏”
- react-native - 如何根据商店价值为 React Navigation Material 底部选项卡呈现选项卡项?
- spring - 由于缺少依赖项,Spring boot junit test @JpaDataTest 无法正常工作