[英]event.preventDefault() not working
I had button which had onclick function 我有具有onclick功能的按钮
<div id="canvas">
<button onclick="document.location.href='hello.php'">Go</button>
</div>
Now I want to stop this onclick
event which redirects to hello.php
, so I have written the following jQuery function 现在我想停止重定向到
hello.php
onclick
事件,因此我编写了以下jQuery函数
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
});
This didn't work so I added a return false
but it's still not working. 这没有用,所以我添加了
return false
但仍然没有用。
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
return false;
});
You can view it at Jsfiddle 您可以在Jsfiddle上查看
Note: I do not want to remove onclick of button 注意:我不想删除按钮的onclick
The correct solution is to remove the onclick
from the HTML in the first place. 正确的解决方案是首先从HTML中删除
onclick
。
Assuming that's not possible, you can remove it after the fact: 假设这不可能,您可以在出现以下情况后将其删除:
$("#canvas button").first().prop("onclick", null);
That clears the onclick
property on the element, which removes the handler set up by the onclick
attribute. 这将清除元素上的
onclick
属性,从而删除由onclick
属性设置的处理程序。 (It's a no-op if the button doesn't exist at all.) (如果该按钮根本不存在,则为无操作。)
It's probably worth noting that if the button
is in a form, it will now submit the form, since its onclick
isn't taking the user away from the page. 值得一提的是,如果
button
位于表单中,则它将立即提交表单,因为其onclick
不会使用户离开页面。 (Since button
's default type
is submit
.) (由于
button
的默认type
为submit
。)
您应该只使用removeAttr
jQuery方法:
$('#canvas button').removeAttr('onclick');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.