Click事件在onclick属性中正常工作,但不能作为addeventlistener

问题描述 投票:1回答:2

我有一个有趣的问题,我觉得应该很简单,但这让我感到困惑。我试图简单地跟踪复选框的选中状态(如果选中,请启用按钮,如果未选中,请禁用按钮)。我遇到的问题是,我似乎无法在事件侦听器中正确跟踪复选框的选中状态,但是如果我将其添加为html中的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);

在上面的(无效的)代码中,我得到以下行为:

  • 复选框不会在视觉上选中或取消选中
  • console.log总是打印'unchecked',因此if条件是总是回到真实状态

我感觉浏览器处理这两件事之间存在某种根本的区别,这是我的两难选择的核心,但是我似乎无法弄清楚这是什么。任何帮助,将不胜感激。

P.S。我也尝试在上面的代码中使用事件监听器中的'change'事件而不是click事件,但是我遇到了相同的问题。

javascript checkbox onclick addeventlistener checked
2个回答
1
投票

原因是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>

0
投票

类似于上述答案,您可以通过调用event.preventDefault()方法来阻止默认操作。除此之外,您应该使用onChange事件,而不是单击事件。

© www.soinside.com 2019 - 2024. All rights reserved.