SMILET
2023-07-14 16:33:06
所以我想當(dāng)用戶在輸入框中輸入某個(gè)命令時(shí)運(yùn)行一個(gè)函數(shù)。例如,當(dāng)用戶輸入“我想要一個(gè)冰淇淋三明治”之類的內(nèi)容時(shí),它會(huì)運(yùn)行一個(gè)函數(shù),將 1 個(gè)冰淇淋三明治添加到他們的庫(kù)存中。但如果他們輸入“Gerfabujohn”之類的內(nèi)容,它會(huì)告訴您這不是命令。我已經(jīng)完成了將三明治添加到庫(kù)存的功能,這不是問(wèn)題。這是我的js:function readCommand() { let readInput = document.querySelector('#commandInput').value if (readInput.value = 'I want an ice cream sandwich') { giveIceCreamSandwich() } else { alert(`Not a command`); }}和我的html:<label for="commandFeild"> Enter Command: </label><input type="text" id="commandInput" name="commandFeild"><br><br><button class="triggerInput" onclick="readCommand()"> Run Command </button>在這里,我嘗試使用 querySelector 函數(shù)通過(guò)其 id 查找輸入框的值。到目前為止,這部分似乎有效。我使用 console.log 來(lái)記錄 readInput 的值,它記錄了輸入字段中的正確命令。這是 if 語(yǔ)句根本不起作用。顯然,無(wú)論我輸入什么,它都會(huì)返回 true 并運(yùn)行該函數(shù),而忽略了它為 true 需要滿足的條件。我已經(jīng)花了幾個(gè)小時(shí)尋找解決方案,我真的很驚訝我沒(méi)有找到答案,因?yàn)檫@似乎是輸入語(yǔ)句的主要功能。任何幫助將不勝感激,謝謝!
1 回答

弒天下
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
兩個(gè)問(wèn)題:
=
用于賦值而不是相等檢查 - 你想使用===
.您將
value
輸入存儲(chǔ)到 中readInput
,因此不需要value
從中引用:
function readCommand() {
let readInput = document.querySelector('#commandInput').value
// ↓ no .value, it's already here -----------↑
if (readInput === 'I want an ice cream sandwich') {
// ↑ === vs =
giveIceCreamSandwich()
} else {
alert(`Not a command`);
}
}
添加回答
舉報(bào)
0/150
提交
取消