preventDefault() not working for change event

给你一囗甜甜゛ 提交于 2019-12-01 03:35:58
Fiambre

You can’t use preventDefault on change events because it’s not cancelable:

$("#text1").change(function(e) {
    alert(e.cancelable?"Is cancelable":"Not cancelable");
});

The cancelable property is true only on events that can be prevented.

preventDefault() is to be used to prevent the default behaviour of an element, that default behaviour is baked in to your browser.

Like for instance the behaviour of an anchor tag when clicked is to initiate a sequence of events that will modify the url bar and send a http request (Overly simplistic explanation I know).

By using evt.preventDefault(evt) inside a click event you can stop the default behaviour so that you can do other operations before you action the behaviour, or ignore it all together.

The issue i can see with your example is that the default behaviour of onchange is to deselect the input box, unhighlighting it and I am not sure that is classed as an event (I am pretty sure it isn't). Not for it to be able to stop a function you have attached onchange(). Infact if you were to use a preventDefault(), myFunc() is exactly where it should be.

For an event to be prevented there must be a resultant output, something beyond modifying appearance. e.g. The click of an a tag, the submit of a form, scroll of a container.

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