[英]Click event works correctly in onclick attribute but not as addeventlistener
我有一個有趣的問題,我覺得應該很簡單,但它讓我很難過。 我試圖簡單地跟蹤選中的 state 復選框(如果選中,則啟用按鈕,如果未選中,則禁用按鈕)。 我遇到的問題是我似乎無法正確跟蹤事件偵聽器中復選框的選中 state,但是如果我將其添加為 ZFC35FDC70D5FC69D269883A8ZEZ 中的 onclick 屬性,它就可以工作,並且不知道為什么是。
具有 html onclick 屬性的工作代碼:
Html:
<input type='checkbox' name='check' id='consent' onclick='checkConsent()'>
<label for='check'>Lorem ipsum</label>
<button id='consentBtn' disabled>Agree</button>
JS:
const dialogConsentBtn = document.getElementById('consentBtn');
const consentCheck = document.getElementById('consent');
const checkConsent = () => {
if (consentCheck.checked === true) {
console.log('checked');
dialogConsentBtn.disabled = false;
} else {
console.log('unchecked');
dialogConsentBtn.disabled = true;
}
}
帶有事件偵聽器的非工作代碼:
HTML:
<input type='checkbox' name='check' id='consent'>
<label for='check'>Lorem ipsum</label>
<button id='consentBtn' disabled>Agree</button>
JS:
const dialogConsentBtn = document.getElementById('consentBtn');
const consentCheck = document.getElementById('consent');
consentCheck.addEventListener('click', (event) => {
event.preventDefault();
if (consentCheck.checked === true) {
console.log('checked');
dialogConsentBtn.disabled = false;
consentCheck.checked = true;
} else {
console.log('unchecked');
dialogConsentBtn.disabled = true;
consentCheck.checked = false;
}
}, false);
在上面的(非工作)代碼中,我得到以下行為:
我有一種感覺,在瀏覽器處理這兩件事的方式之間存在某種根本差異,這是我困境的核心,但我似乎無法弄清楚那是什么。 對此的任何幫助將不勝感激。
PS我還嘗試在事件偵聽器中使用“更改”事件而不是單擊事件來執行上述代碼,但我遇到了同樣的問題。
原因是a)您是復選框事件上的event.preventDefault()
,這將阻止它被選中;b)如果它被選中,您會立即使用同意檢查consentCheck.checked = false
取消選中它。 對於同意按鈕,您也有相反的邏輯,因此您在選中復選框時禁用它,並在未選中復選框時啟用它。
因此,由於這兩個原因,無法選中第二個示例中的復選框,請參見下文:
const dialogConsentBtn = document.getElementById("consentBtn"); const consentCheck = document.getElementById("consent"); consentCheck.addEventListener( "click", (event) => { // event.preventDefault(); if (consentCheck.checked === true) { console.log("checked"); dialogConsentBtn.disabled = false; // was true // consentCheck.checked = false; } else { console.log("unchecked"); dialogConsentBtn.disabled = true; // was false // consentCheck.checked = true; } }, false );
<input type="checkbox" name="check" id="consent" /> <label for="check">Lorem ipsum</label> <button id="consentBtn" disabled>Agree</button>
像上面的答案一樣,您通過調用 event.preventDefault() 方法來阻止默認操作。 除此之外,您應該使用 onChange 事件而不是單擊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.