【问题标题】:javascript + preventDefault and stopPropagation not working in addEventListenerjavascript + preventDefault 和 stopPropagation 在 addEventListener 中不起作用
【发布时间】:2017-09-05 16:17:30
【问题描述】:

我有表单并使用 addEventListener 进行表单提交,我试图在表单提交后停止页面加载。

注意:我想使用 addEventListener 函数。

var test = document.querySelector('.submit');
test.addEventListener('click', checkFunction);

function checkFunction (){
  console.log(test);
  this.preventDefault();
  this.`stopPropagation`();
}
<form>
<input type="text" >
<input type="submit" value="submit" name="submit" class="submit">
</form>

【问题讨论】:

  • 为什么stopPropagation前后都有一个“`”?
  • @PaulFitzgerald 很可能是由于帖子的格式。
  • 你为什么要在stopPropagation()987654323@之前加''

标签: javascript addeventlistener


【解决方案1】:

您需要使用event 而不是this,其中event 指的是传递给您的回调函数的事件参数。在您的情况下,this 只是指提交按钮。

JSFiddle

Live Example

打开控制台比较e(事件)和this

【讨论】:

    【解决方案2】:

    您可以添加 event 而不是 this 并且可以使用:

    var test = document.querySelector('.submit');
    test.addEventListener('click', checkFunction);
    
    function checkFunction (event){
        event.preventDefault();
        event.stopPropagation();
    
        console.log(event);
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2013-07-23
      相关资源
      最近更新 更多