[英]How to implement .includes in JavaScript
我正在使用 JS 和 HTML 開發一個非常簡單的聊天機器人,我有以下代碼輸出“答案”作為對用戶所問內容的答復。 這很好用,但是當我嘗試實現.includes以檢查是否已詢問某個短語時,它不再輸出任何內容。 例如,如果用戶問“can you help”,它應該 output 得到與“help”相同的答案,因為它包含“help”關鍵字。 沒有.includes代碼工作正常。
function talk() {
var know = {
"Hey": "Hello!",
"Help": `You can find help by clicking <a href='https://addressname.com'target="_blank">here</a>`
};
var user = document.getElementById('userBox').value;
document.getElementById('chatLog').innerHTML = user + "<br>";
if (user in know) {
document.getElementById.includes('chatLog').innerHTML = know[user] + "<br>";
} else {
document.getElementById('chatLog').innerHTML = "I do not understand.";
}
}
我想你需要改變下面的行
document.getElementById.includes('chatLog').innerHTML
作為
document.getElementById('chatLog').innerHTML.includes(user)
includes() 方法確定數組是否在其條目中包含某個值,並根據需要返回 true 或 false。
希望這可以幫助:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
更新:
var know = {
"Hey": "Hello!",
"Help": `You can find help by clicking <a href='https://addressname.com' target="_blank">here</a>`
};
function goo() {
var userBox = document.getElementById('userBox');
var userInput = userBox.value;
var chatLog = document.getElementById('chatLog');
var chatLogContent = "";
if (!userInput) {
chatLogContent = 'Please enter some value'
}
var hasKeyword = false;
for (var key in know) {
if (userInput.toLowerCase().includes(key.toLowerCase())) {
hasKeyword = true;
break;
}
}
if (hasKeyword) {
chatLogContent += know[key] + "<br>"; //or use know.key
} else {
chatLogContent += "I do not understand.<br>";
}
var client = document.createElement('div');
client.setAttribute('class', 'client');
client.innerHTML += userInput + "<br>";
chatLog.appendChild(client);
var server = document.createElement('div');
server.setAttribute('class', 'server');
server.innerHTML = chatLogContent;
chatLog.appendChild(server);
}
更新
這應該有幫助:
https://jsfiddle.net/smileyface/948bg03n/1/
嗯,我不擅長 css。但它工作得很好。 每次單擊按鈕時滾動瀏覽。
在這里試試 - Localhost 聊天框在這里: https://jsfiddle.net/smileyface/948bg03n/1/show
更新
正如您在評論中所問,
這只會顯示當前評論
if(hasKeyword){
chatLogContent = know[key] + "<br>"; //or use know.key
}else{
chatLogContent = "I do not understand.<br>";
}
chatLog.innerHTML = chatLogContent;
includes() 方法確定數組是否在其條目中包含某個值,並根據需要返回 true 或 false。
getElementById 也是一個 function ,它需要一個元素的 id 作為參數。
如果要更改具有 id chatLog
的元素的內部 HTML,則必須按以下方式進行。
if (user in know) {
document.getElementById('chatLog').innerHTML = know[user] + "<br>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.