javascript - JavaScipt 中的输入处理
问题描述
我是 Web 开发(包括 JavaScript 和 HTML)的新手,并且在我的个人项目中遇到了一些似乎没有明确修复的问题。
概述
我的项目是从网站上的用户那里获取输入,并将其提供给我的后端以输出单词完成建议列表。
例如,输入 => "bass",那么程序会建议 "bassist"、"bassa"、"bassalia"、"bassalian"、"bassalan" 等作为模式 "bass" 的可能补全(这些是单词从英语词典文本文件中提取)。
后端 - 在 Node JS 库上运行
trie.js file:
/* code for the trie not fully shown */
var Deque = require("collections/deque"); // to be used somewhere
function add_word_to_trie(word) { ... }
function get_words_matching_pattern(pattern, number_to_get = DEFAULT_FETCH) { ... }
// read in words from English dictionary
var file = require('fs');
const DICTIONARY = 'somefile.txt';
function preprocess() {
file.readFileSync(DICTIONARY, 'utf-8')
.split('\n')
.forEach( (item) => {
add_word_to_trie(item.replace(/\r?\n|\r/g, ""));
});
}
preprocess();
module.exports = get_words_matching_trie;
前端
呈现网站视觉效果的 HTML 脚本,以及从用户那里获取输入并将其传递到后端脚本以获得可能的建议。它看起来像这样:
index.html script:
<!DOCTYPE HTML>
<html>
<!-- code for formatting website and headers not shown -->
<body>
<script src = "./trie.js">
function get_predicted_text() {
const autofill_options = get_words_matching_pattern(input.value);
/* add the first suggestion we get from the autofill options to the user's input
arbitrary, because I couldn't get this to actually work. Actual version of
autofill would be more sophisticated. */
document.querySelector("input").value += autofill_options[0];
}
</script>
<input placeholder="Enter text..." oninput="get_predicted_text()">
<!-- I get a runtime error here saying that get_predicted_text is not defined -->
</body>
</html>
我得到的错误
首先,我得到客户端未定义“require()”的明显错误。这个,我用browserify修复。
其次,作为 node.js 模块,客户端不存在“fs”的问题。我尝试使用 node 运行 trie.js 文件并使用一些服务器端代码处理它:
function respond_to_user_input() {
fs.readFile('./index.html', null, (err, html) => {
if (err) throw err;
http.createServer( (request, response) => {
response.write(html);
response.end();
}).listen(PORT);
});
respond_to_user_input();
}
有了这个,我不完全确定如何编辑文档元素,例如更改input.value
index.html,或在输入字段中调用oninput
事件侦听器。此外,如果我通过node trie.js
终端中的命令调用 HTML 文件,则不会调用我的 CSS 格式化脚本。
这给我留下了一个问题:是否甚至可以直接运行 index.html(通过 Google Chrome)并在调用 trie.js 脚本时让它使用节点 JS 模块?我可以使用 HTTP 模块在上面描述的服务器端代码,我如何解决调用我的外部 CSS 脚本(我的 HTML 文件发送一个 href 到)和访问 document.querySelector("input") 来编辑我的输入的问题场地?
解决方案
推荐阅读
- python - 创建后重新缩放 matplotlib.colorbar 和 matplotlib.contour
- html - 下拉菜单角内的下拉菜单
- php - 非法字符串偏移 'nom_banque'
- python - 获取字典以返回值,这是一个列表
- android - android包装内容容器,使孩子碰撞并设置向右对齐
- c++ - C++中值类别定义中的“身份”是什么意思
- php - xDebug 在 Mac 上的安装问题
- onelogin - 验证码流错误 - 缺少必需的参数。(授予类型)
- azure - 无法创建运行方式帐户,我在订阅中确实拥有所有者权限
- sse - 是否所有支持 AVX2 的 CPU 也支持 SSE4.2 和 AVX?