preventDefault()不会阻止该操作 [英] preventDefault() doesn't prevent the action

查看:197
本文介绍了preventDefault()不会阻止该操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在链接上使用event.preventDefault()时,它可以工作,但是当我在按钮上使用时,则不行!

When I use event.preventDefault() on a link it works, however when I use it on a button doesn't!

演示

我的代码:

<a id="link" href="http://www.google.com">link</a>
<button id="button" onclick="alert('an alert')">button</button>​

$('#link').click(function(event){
  event.preventDefault();
});
$('#button').click(function(event){
  event.preventDefault();
});

链接动作被取消,但是当我单击按钮时,仍执行onClick动作.

​ Link action is cancelled, but when I click on the button, still executes the onClick action.

有帮助吗?我想做的是在不更改按钮html的情况下防止onClick按钮 (我知道该怎么做

Any help? what I want to do is to prevent the button onClick action without changing the button html (I know how to do

$('#button').removeAttr('onclick');

推荐答案

如果一个元素上有多个事件处理程序,并且想要阻止其他事件处理程序执行,则需要event.stopImmediatePropagation();. preventDefault()仅阻止默认操作(例如,提交表单或导航到另一个URL),而stopImmediatePropagation()阻止事件使DOM树冒泡, 阻止同一元素上的任何其他事件处理程序被执行.

You want event.stopImmediatePropagation(); if there are multiple event handlers on an element and you want to prevent the others to execute. preventDefault() just blocks the default action (such as submitting a form or navigating to another URL) while stopImmediatePropagation() prevents the event from bubbling up the DOM tree and prevents any other event handlers on the same element from being executed.

以下是一些有用的链接,介绍了各种方法:

Here are some useful links explaining the various methods:

  • http://api.jquery.com/event.preventDefault/
  • http://api.jquery.com/event.stopPropagation/
  • http://api.jquery.com/event.stopImmediatePropagation/

但是,由于它仍然不起作用,这意味着onclick=""处理程序将在附加的事件处理程序之前执行.自从代码运行onclick代码以来,您就无能为力了.

However, since it still doesn't work it means that the onclick="" handler executes before the attached event handler. There's nothing you can do since when your code runs the onclick code has already been executed.

最简单的解决方案是完全删除该处理程序:

The easiest solution is completely removing that handler:

$('#button').removeAttr('onclick');

即使通过纯JavaScript( addEventListener() )添加事件监听器, useCapture=true没有帮助-显然内联事件甚至在事件开始下降到DOM树之前就触发了.

Even adding an event listener via plain javascript (addEventListener()) with useCapture=true doesn't help - apparently inline events trigger even before the event starts descending the DOM tree.

如果只是因为需要而不想删除该处理程序,只需将其转换为正确附加的事件即可:

If you just do not want to remove the handler because you need it, simply convert it to a properly attached event:

var onclickFunc = new Function($('#button').attr('onclick'));
$('#button').click(function(event){
    if(confirm('prevent onclick event?')) {
        event.stopImmediatePropagation();   
    }
}).click(onclickFunc).removeAttr('onclick');

这篇关于preventDefault()不会阻止该操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆