preventDefault()不起作用 [英] preventDefault() doesn't work

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

问题描述

当我在链接上使用event.preventDefault()时,它会起作用,但是当我在按钮上使用它时却没有!

DEMO

我的代码:

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

<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行动

任何帮助?我想要做的是阻止按钮onClick动作而不更改按钮html (我知道该怎么做)

$('#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天全站免登陆