很抱歉,如果之前已经这样做过,但我找不到与我的问题足够相关的问题。
我正在设置一个带有文本框的简单 HTML 页面,类似于聊天机器人的操作。 问题是,如果用户输入精确的字符串,我需要显示预设答案。到目前为止,我只能有两种特定的输出:一种是如果特定字符串签入,另一种是如果没有签入。当我添加更多内容时,输出会经历多个选项,它会有点混乱,如果触发,它应该只返回特定答案,如果未触发,则返回默认答案。 如果我不清楚,这里是一个视觉效果和我的一些代码(可能很混乱,我不是高级用户):
function handleKeyPress(event) {
if (event.key === 'Enter') {
processInput();
}
}
function processInput() {
var inputElement = document.getElementById('input');
var outputElement = document.getElementById('output');
var inputValue = inputElement.value;
// move input to output div
outputElement.innerHTML += inputValue + '<br>';
// keep output focus on latest entries
outputElement.scrollTop = outputElement.scrollHeight;
// append text after a delay
function appendTextWithDelay(text, delay) {
setTimeout(function() {
outputElement.innerHTML += text + '<br>';
// Scroll to the bottom of the output area
outputElement.scrollTop = outputElement.scrollHeight;
}, delay);
}
// check for specific strings
if (inputValue.includes('specific_string')) {
// output delayed response
appendTextWithDelay('specific_answer', 1000);
}
else {
// output delayed default response
appendTextWithDelay('default_answer', 2000);
}
// clear input area
inputElement.value = '';
}
提前致谢!
(尝试堆叠“if”条件,仅使用一个“else”检查) (尝试堆叠完整的“if/else”组)
您可以像这样堆叠
if-else
语句:
if (x.includes('a')) appendText('answer_a')
else if (x.includes('b')) appendText('answer_b')
else if (x.includes('c')) appendText('answer_c')
else if (x.includes('d')) appendText('answer_d')
else if (x.includes('e')) appendText('answer_e')
else appendText('answer_default')