我有一個使用 node、express 和 ejs 作為視圖引擎構建的 Web 應用程式。在特定頁面上,我有一個事件偵聽器,它將在按鍵時轉到主頁,如下所示:
<script>
document.addEventListener("keypress", function onPress(event) {
window.location = ('/home');
});
</script>
問題是我在該頁面上還有一個按鈕,按下該按鈕時會顯示一個包含文本輸入的引導模式元素,因此當模式打開并且用戶嘗試輸入某些輸入時,會觸發事件偵聽器。有沒有辦法在模式關閉之前忽略此事件偵聽器?
我嘗試給 DOM(不包含模態)一個 tabindex 以使其可選擇并將事件偵聽器放在上面,但是用戶必須在觸發事件偵聽器之前單擊頁面,這并不理想
uj5u.com熱心網友回復:
這里最好的方法是跟蹤modalOpenState一個布爾變數。當模態打開時,將其設定為true,并false在關閉時設定。并且當您在偵聽keypress事件時,檢查modalOpenState是真還是假,然后相應地重定向。
注意:正如 Zameer 的評論還指出的,“keypress”事件已被棄用,并且可以隨時停止作業。MDN 建議根據要求用beforeinput或keydown事件替換它。
uj5u.com熱心網友回復:
您可以通過使用防止eventininput向上傳播,然后用戶輸入將不會觸發檔案偵聽器。documentevent.stopPropagationkeypress
document.addEventListener("keypress", function (event) {
console.log("event", event);
console.log("keyPress");
});
const input = document.getElementById("user-input");
input.addEventListener("keypress", function (e) {
e.stopPropagation();
});
const btn = document.getElementById("hello-btn");
btn.addEventListener("click", function onClick(e) {
console.log("clicked btn");
});
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="hello-btn">Say hello</button>
<input id="user-input" placeholder="enter text" />
</div>
<script src="src/index.js"></script>
</body>
</html>
但是,我建議不要將keypress事件附加到document. 根據 MDN,它已被棄用:https : //developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event#browser_compatibility。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357753.html
標籤:javascript html 节点.js ejs
