javascript preventDefault() 不适用于更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24251955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:28:08  来源:igfitidea点击:

preventDefault() not working for change event

javascriptonchangepreventdefault

提问by SlimJim

Any ideas why preventDefault is not working? Here's the code below . . . Tks!

任何想法为什么 preventDefault 不起作用?这是下面的代码。. . 太棒了!

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

    $(document).ready(function() {
        $("#text1").change(function(e) {
             e.preventDefault();
        });
    });

function myFunc() {
    alert("Random, annoying alert");
}

</script>
</head>

Just one HTML element in the form:

表单中只有一个 HTML 元素:

<body>
<form name="test" method="post">
    <input name="text1" id="text1" type="text" onchange="myFunc();">
</form>
</body>

回答by Fiambre

You can't use preventDefaulton change events because it's not cancelable:

您不能preventDefault在更改事件上使用,因为它不可取消:

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

The cancelableproperty is true only on events that can be prevented.

cancelable属性仅对可以阻止的事件为真。

回答by Chris Rymer

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

preventDefault()用于防止元素的默认行为,该默认行为已融入您的浏览器。

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).

例如,单击锚标记时的行为是启动一系列事件,这些事件将修改 url 栏并发送 http 请求(我知道过于简单的解释)。

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.

通过evt.preventDefault(evt)在单击事件中使用,您可以停止默认行为,以便您可以在操作该行为之前执行其他操作,或者一起忽略它。

The issue i can see with your example is that the default behaviour of onchangeis 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.

我可以在您的示例中看到的问题是,默认行为onchange是取消选择输入框,取消突出显示它,我不确定它是否被归类为事件(我很确定它不是)。不是因为它能够停止您附加的功能onchange()。事实上,如果你要使用preventDefault(),myFunc()正是它应该在的地方。

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.

对于要阻止的事件,必须有结果输出,而不仅仅是修改外观。例如,a 标签的点击、表单的提交、容器的滚动。