event.preventDefault()究竟如何影响DOM? [英] How exactly does event.preventDefault() affect the DOM?

查看:129
本文介绍了event.preventDefault()究竟如何影响DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于某人的建议,我添加了这一行 $('body')。on('touchstart',function(event){event.preventDefault()}) in我的手机网络应用程序禁用iOS中弹出的本机应用程序。它很适合禁用反弹,但在DOM中的其他位置给我一些奇怪的行为。

点击不起作用的事件等。我希望更好地理解它的作用以及如何解决它在DOM中其他地方的影响。



谢谢!

编辑:

I有两行:

$ $ $ $'code $('body')。on('touchstart',function(e){e.preventDefault ()';
$('#home')。on('click',function(){alert('home')};

如果我注释掉 preventDefault 行,那么 #home 如果我将它放在#home行中并没有响应 #home 只是嵌套在 body

任何想法都可能导致这种行为?它是更大代码库的一部分,所以它很难给你所有的细节,但我不知道甚至知道从哪里开始。



再次感谢!

解决方案

e.preventDefault()告诉浏览器,如果此对象上有此事件的默认行为,则跳过该默认行为。



因此,例如,如果您有一个提交按钮的默认t行为是提交一个表单,并且该按钮上有一个单击处理程序,它执行了 preventDefault(),那么当点击按钮时浏览器不会提交表单。这种经典用法可能是当表单不验证时,您向用户显示错误消息并且不希望将表单提交给服务器。



或者另一个例子。如果您为链接设置了点击处理程序,并且您在该点击处理程序中调用 e.preventDefault(),那么浏览器将不会处理点击链接,也不会请按照链接中的href。


Based on someone's advice I added this line $('body').on('touchstart', function(event){ event.preventDefault() }) in my mobile webapp to disable the native app bouncing in iOS. It works great for disabling the bounce but gives me some weird behavior elsewhere in DOM.

Click events that don't work, etc. I was hoping to get a better understanding of what this does and how to work around it's effects elsewhere in the DOM.

Thanks!

EDIT:

I have these two lines:

  $('body').on('touchstart', function(e){ e.preventDefault() };
  $('#home').on('click', function(){ alert('home') };

If I comment out the preventDefault line then the #home line works. If I leave it in the #home line doesn't respond. #home is just a div nested in the body.

Any idea what could be causing this behavior? It's part of a bigger codebase so it;s hard to give you all the details but I don't even know where to start.

Thanks Again!

解决方案

e.preventDefault() tells the browser that if there is a default behavior for this event on this object, then skip that default behavior.

So, for example, if you had a submit button that the default behavior was to submit a form and you had a click handler on that button that did a preventDefault(), then the browser would not submit the form when the button was clicked. A classic use of this might be when the form doesn't validate so you show the user an error message and don't want the form to be submitted to the server.

Or another example. If you set up a click handler for a link and you call e.preventDefault() in that click handler, then the browser will not process the click on the link and will not follow the href in the link.

这篇关于event.preventDefault()究竟如何影响DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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