<div class="searchbarhome">
<button id="glas" onclick="myFunction()"for="search"><i class="fa fa-search" aria-hidden="true"></i></button>
<input class="searchbox" type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
</div>
這是我的html代碼
function myFunction(){
console.log('test');
// // Get the input field
var el = document.getElementById("myInput");
el.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
var input = document.getElementById("myInput").value;
console.log(input)
localStorage.setItem("storageName",input);
console.log('Sending data');
document.location = 'search.php';
}
})
這是我的js代碼
如您所見,我有一個按鈕和一個輸入。該功能適用??于輸入,但我也希望能夠按下按鈕。現在我不知道我該怎么做才能讓函式檢查 keydown 和 mouseup 事件
uj5u.com熱心網友回復:
您當前的邏輯是錯誤的:在 HTML 中,您已將處理程式myFunction作為keyup處理程式附加到input元素,但在內部myFunction,您再次將事件處理程式附加到input元素。這實際上意味著每次用戶在輸入控制元件中釋放一個鍵時,都會為該input元素累積一個新的事件處理程式。這是要積累...
相反,從您的 HTML 中洗掉onclick和keypress屬性并addEventListener僅使用。
其他一些問題:
- 存盤某些
localStorage內容不會將字串發送到 PHP 服務器。 - 該
for屬性對button元素沒有意義。
然后是您的核心問題:只需將公共部分與兩個事件應該做的事情分開。由于對 Enter 鍵的檢查僅針對input元素上的事件(而不針對按鈕事件),因此該部分不應在通用功能中。
這是它的外觀:
const inputElem = document.getElementById("myInput");
const buttonElem = document.getElementById("glas");
inputElem.addEventListener("keypress", (e) => {
if (e.key === "Enter") process();
});
buttonElem.addEventListener("click", process);
function process() { // Function with the common logic
// Common code:
console.log('test', inputElem.value);
// Other logic...
}
<div class="searchbarhome">
<button id="glas">Search</button>
<input class="searchbox" type="text" id="myInput" placeholder="Zoek workshops.." title="Type in a name">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/507715.html
標籤:javascript html
