How exactly does event.preventDefault() affect the DOM?

淺唱寂寞╮ 提交于 2019-12-19 07:32:37

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/11921210/how-exactly-does-event-preventdefault-affect-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!