我的html代碼如下:
<input type="text" id="emp" onkeypress="return (event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" >
它禁止在輸入欄位中輸入任何數字。現在,我想keypress在我的js. 所以我嘗試執行:
if(condition)
document.getElementById("emp").removeEventListener("keypress");
但它拋出一個錯誤:
未捕獲的型別錯誤:無法在“EventTarget”上執行“removeEventListener”:需要 2 個引數,但僅存在 1 個。
如何洗掉事件?
uj5u.com熱心網友回復:
HTML 標簽上的屬性就像一個函式和一個事件監聽器。為了實作您的目標,您只需要編輯或洗掉該屬性
if(condition)
document.getElementById("emp").setAttribute("onkeypress", "");
if(condition)
document.getElementById("emp").removeAttribute("onkeypress");
uj5u.com熱心網友回復:
這是一種方法:
<input type="text" id="emp" oninput="console.log(this.value)" >
<button onclick='document.querySelector("input").oninput=null'>remove event</button>
uj5u.com熱心網友回復:
型別和偵聽器是 removeEventListener 的必需引數。偵聽器根據其型別和要移除的事件處理程式的 EventListener 函式從事件目標中移除。
因此,在偵聽器的位置,您應該像下面這樣放置一個空值。希望它會起作用。
document.getElementById("emp").removeEventListener('onkeypress',null);
uj5u.com熱心網友回復:
你可以讓它更容易。如果條件為真,您可以設定 return false 來代替洗掉事件。在此示例中,如果值長度大于 3 個字符,則條件將切換。
// const i = document.querySelector('input');
function myF(event)
{
const charCode = event.keyCode;
const condition = event.target.value.length < 3 ? false : true;
if (condition) {
console.log('condition true');
return false;
}
if ((charCode > 64 && charCode < 91) ||
(charCode > 96 && charCode < 123) ||
charCode == 8) {
return true; }
else {
return false;
}
}
<input type="text" id="emp" onkeypress="return myF(event)" >
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402019.html
標籤:javascript html
